1

I need a way to convert this string "foo/bar/test/hello" into this

foo = {
  bar = {
    test = {
      hello = {},
    },
  },
}

Thanks.

3 Answers 3

3

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 .

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.