Originally Posted by Torhal
Building tables programmatically isn't going to save you anything, IMO. You can do the same thing you were doing with the if checks, but in a more terse manner:
Code:
ADVANCED_INTERFACE_GLOBAL_CONSTANTS = ADVANCED_INTERFACE_GLOBAL_CONSTANTS or {}
ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS = ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS or {}
ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS.ADVANCED_USER_INTERFACE = ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS.ADVANCED_USER_INTERFACE or {}
I omitted the last one because checking if a table is nil then setting it to nil if so makes no sense to me.
|
Originally Posted by Barjack
The problem with your code is that you can't use _G to look for tables in tables like that. For example, _G["one.two.three"] is looking for a single key in the global table with the value "one.two.three", it's not looking for table "one" then finding its key "two" then finding its key "three" etc., like it would if you wrote one.two.three in code.
Whether this is a good idea or not I don't know, but you can fix your code by avoiding using the global object like that. Here's a slightly different and working example:
Code:
function generate_subtables(str)
local base = {}
local current = base
for token in string.gmatch(str, '([^.]+)') do
local t = {}
current[token] = t
current = t
print(token)
end
return base
end
ADVANCED_INTERFACE_GLOBAL_CONSTANTS = generate_subtables("STAMPS.ADVANCED_USER_INTERFACE.VERSION")
print(ADVANCED_INTERFACE_GLOBAL_CONSTANTS)
print(ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS)
print(ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS.ADVANCED_USER_INTERFACE)
print(ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS.ADVANCED_USER_INTERFACE.VERSION)
You can evaluate it here: https://repl.it/BSKi
|
Thank you very much
Torhal and
Barjack! You saved my day! I very appreciate your answer and help.
Regarding to last code example, I was not able to use it, because it's not checking existing tables. For example, I already got a table with some values, I don't want to touch them or delete, instead, I would like to add some new tables in it:
https://repl.it/BSKi/1
Lua Code:
ADVANCED_INTERFACE_GLOBAL_CONSTANTS = {}
ADVANCED_INTERFACE_GLOBAL_CONSTANTS.TEST = "TEST"
function generate_subtables(str)
local base = {}
local current = base
for token in string.gmatch(str, '([^.]+)') do
local t = {}
-- I tryed to add "if not current[token] then" but looks like it's a wrong way to check if table is exists.
current[token] = t
current = t
print(t)
end
return base
end
ADVANCED_INTERFACE_GLOBAL_CONSTANTS = generate_subtables("STAMPS.ADVANCED_USER_INTERFACE.VERSION")
print(ADVANCED_INTERFACE_GLOBAL_CONSTANTS)
print(ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS)
print(ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS.ADVANCED_USER_INTERFACE)
print(ADVANCED_INTERFACE_GLOBAL_CONSTANTS.STAMPS.ADVANCED_USER_INTERFACE.VERSION)
-- Next line will print nil instead of "TEST"
print(ADVANCED_INTERFACE_GLOBAL_CONSTANTS.TEST) -- SHOULD PRINT "TEST"