Lua 将字符串转换为多维数组

我需要一种将这个字符串 "foo/bar/test/hello" 转换为以下形式的方法

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

谢谢。

点赞
用户107090
用户107090

递归是自然的工具。这里是一种解决方案。为简单起见,convert 返回一个表格。

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)

如果您真的需要设置全局变量 foo,则在最后执行以下操作:

k,v=next(z); _G[k]=v
print(foo)
2017-03-09 02:07:04
用户3435777
用户3435777

你可以使用 string.gmatch 来分割字符串,然后构建你想要的表格,可以尝试这样做:

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)

提示:这里使用了 pprint 来打印表格。

2017-03-09 02:57:19
用户3735873
用户3735873

以下是另一种(非递归)可能性:

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'
2017-03-09 10:34:59