74 posts
Location
~
Posted 08 March 2017 - 09:31 PM
I need to find a way to convert this string
"test/foo/bar"
into this table
test = { foo = { bar = {} } }
.
3057 posts
Location
United States of America
Posted 08 March 2017 - 10:40 PM
You could do this with a simple pattern and the gmatch function. Try that and ask more specific questions if you get stuck.
34 posts
Posted 09 March 2017 - 07:20 PM
function getTable(words)
local newTable = {}
if #words > 1 then
newTable[words[1]] = getTable({unpack(words, 2, #words)})
else
newTable[words[1]] = {}
end
return newTable
end
function makeTable(string)
local words = {}
for w in (string .. "/"):gmatch("([^/]*)/") do table.insert(words, w) end
return getTable(words)
end
assert(makeTable("test/foo/bar"), {test = { foo = { bar = {} } } })
This is almost what you asked for, though if you want to make a global variable named test, you can do so dynamically by doing the following
nameOfVariable = "test"
_G[nameOfVariable] = "value"
this is the same as
test = "value"