分割字符串的所有示例都会生成数组。我想要以下
给定x.y.z
之类的字符串,例如storage.clusters.us-la-1
如何从类似的
x = {
y = {
z = {
}
}
}
答案 0 :(得分:2)
Below is a function that should do what you want.
function gen_table(str, existing)
local root = existing or {}
local tbl = root
for p in string.gmatch(str, "[^.]+") do
local new = tbl[p] or {}
tbl[p] = new
tbl = new
end
return root
end
Usage:
local t = gen_table("x.y.z")
local u = gen_table("x.y.w", t)
t.x.y.z.field = "test1"
t.x.y.w.field = "test2"