有没有办法将层次结构字符串转换为表形式?
假设输入为A.B.C.D
ouput应该是一个遍历以上输入的表:A = {}
A.B = {}
A.B.C = {}
A.B.C.D = {}
谢谢。
显而易见的解决方案是解析字符串并以此构建层次结构表。但一个更聪明的解决方案是让lua为你做这件事。只要有一点超敏捷和功能环境操作,就可以做到这一点:
dump = require 'pl.pretty'.dump -- convenient table dumper from penlight
function createtable(str)
local env_mt = {}
env_mt.__index = function(t, k)
rawset(t, k, setmetatable({}, env_mt))
return rawget(t, k)
end
local env = setmetatable({}, env_mt)
local f = loadstring("return "..str)
setfenv(f, env)
f()
return env
end
dump( createtable "A.B.C.D" )
该输出:
{
A = {
B = {
C = {
D = {
}
}
}
}
}
@greatwolf的答案是正确的,但我更喜欢更直接的方法,即"解析"字符串并构建表。魔术少了,而且你不执行从(可能)用户定义的字符串加载的函数,这将是一个安全问题。
local createtable = function(str)
local top = {}
local cur = top
for i in str:gmatch("[^.]+") do
cur[i] = {}
cur = cur[i]
end
return top
end
(require "pl.pretty").dump(createtable("A.B.C.D"))