I need a way to convert this string "foo/bar/test/hello" into this
foo = {
bar = {
test = {
hello = {},
},
},
}
Thanks.
you can use string.gmatch to split it, then just build the table you want, try this:
local pprint = require('pprint')
example="foo/bar/test/hello"
v={}
s=v
for i in string.gmatch(example, "(%w+)") do
v[i]={}
v=v[i]
end
pprint(s)
PS. in order print table, i use pprint here .
Recursion is the natural tool to use. Here is one solution. For simplicity, convert returns a table.
S="foo/bar/test/hello"
function convert(s)
local a,b=s:match("^(.-)/(.-)$")
local t={}
if a==nil then
a=s
t[a]={}
else
t[a]=convert(b)
end
return t
end
function dump(t,n)
for k,v in pairs(t) do
print(string.rep("\t",n)..k,v)
dump(v,n+1)
end
end
z=convert(S)
dump(z,0)
If you really need to set a global variable foo, then do this at the end:
k,v=next(z); _G[k]=v
print(foo)
Here's another (non-recursive) possibility:
function show(s)
local level = 0
for s in s:gmatch '[^/]+' do
io.write('\n',(' '):rep(level) .. s .. ' = {')
level = level + 2
end
for level = level-2, 0, -2 do
io.write('}',level > 0 and ',\n' or '\n',(' '):rep(level-2))
end
end
show 'foo/bar/test/hello'