【发布时间】:2017-03-09 20:26:11
【问题描述】:
我需要一种方法将这个字符串 "foo/bar/test/hello" 转换成这个
foo = {
bar = {
test = {
hello = {},
},
},
}
谢谢。
【问题讨论】:
标签: lua
我需要一种方法将这个字符串 "foo/bar/test/hello" 转换成这个
foo = {
bar = {
test = {
hello = {},
},
},
}
谢谢。
【问题讨论】:
标签: lua
你可以使用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)
PS。为了打印表格,我在这里使用pprint。
【讨论】:
递归是使用的自然工具。这是一种解决方案。为简单起见,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)
【讨论】:
这是另一种(非递归)可能性:
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'
【讨论】: