Lua将字符串转换为更多数组
我需要一种方法将这个字符串foo/bar/test/hello转换为Lua将字符串转换为更多数组,lua,Lua,我需要一种方法将这个字符串foo/bar/test/hello转换为 foo = { bar = { test = { hello = {}, }, }, } 谢谢。递归是自然使用的工具。这里有一个解决方案。为简单起见,convert返回一个表 S="foo/bar/test/hello" function convert(s) local a,b=s:match("^(.-)/(.-)$") local t={} if a==ni
foo = {
bar = {
test = {
hello = {},
},
},
}
谢谢。递归是自然使用的工具。这里有一个解决方案。为简单起见,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)
递归是自然使用的工具。这里有一个解决方案。为简单起见,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)
您可以使用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)
注:为了打印表格,我在这里使用。您可以使用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)
注:为了打印表格,我在这里使用。这里有另一种非递归的可能性:
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'
这是另一种非递归的可能性:
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'