将 Lua 字符串拆分成带有子表的表格。

所有拆分字符串的示例都生成数组。我想要以下内容

给定像x.y.z这样的字符串,例如storage.clusters.us-la-1,我该如何生成类似下面这样的表格

x = {
  y = {
    z = {
    }
  }
}
点赞
用户142162
用户142162

以下是一个函数,应该可以做到你想要的。

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

使用方法:

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"
2015-09-29 00:45:39