Lua Table Access with Location Given as a String
Lua Table Access with Location Given as a String
I have a table and I'm trying to access a specific location that is passed in as a String. What is the easiest way to use the string to access the correct location?
Example, if the table looks like this:
a.b1 = true
a.b2.c1 = true
a.b2.c2 = false
a.b3 = true
How can I change a.b2.c2 to true given a location 'a.b2.c2' as a string.
a[str_var]
2 Answers
2
If you have just a single level, you can use square-brace indexing:
function setSingle(obj, key, value)
obj[key] = value
end
setSingle(a, "b1", "foo")
print(a.b1) --> foo
If you have multiple, you need to do several iterations of this indexing. You can use a loop to do that:
function setMultiple(obj, keys, value)
for i = 1, #keys - 1 do
obj = obj[keys[i]]
end
-- Merely "obj = value" would affect only this local variable
-- (as above in the loop), rather than modify the table.
-- So the last index has to be done separately from the loop:
obj[keys[#keys]] = value
end
setMultiple(a, "b2", "c1", "foo")
print(a.b2.c1) --> foo
You can use string.gmatch
to parse a properly formatted list of keys. [^.]+
will match "words" made of non-period symbols:
string.gmatch
[^.]+
function parseDots(str)
local keys =
for key in str:gmatch "[^.]+" do
table.insert(keys, key)
end
return keys
end
Putting this all together,
setMultiple(a, parseDots("b2.c2"), "foo")
print(a.b2.c2) --> foo
One issue you may run into is that you cannot create new tables with this function; you will have to create the containing table before you can create any keys in it. For example, beforing ading "b4.c3"
you would have to add "b4"
.
"b4.c3"
"b4"
You can use loadstring
to build the statement you want to execute as a string.
loadstring
a = b2 =
a.b1 = true
a.b2.c1 = true
a.b2.c2 = false
a.b3 = true
str = "a.b2.c2"
loadstring(str .. " = true")()
print(a.b2.c2)
Running a full scripting language to write keys to a table is overkill, and could lead to huge security flaws. It also won't work nicely unless your
a
is a global variable.– Curtis F
Aug 28 at 0:18
a
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You can use the key as a string accesing the table like
a[str_var]
but this is not taking into account nested tables– José María
Aug 26 at 16:26