将 Lua 字符串拆分为包含子表的表

Split Lua string into tables with subtables

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

给定的字符串如 x.y.z 例如storage.clusters.us-la-1 如何从类似

生成 table
x = {
  y = {
    z = {
    }
  }
}

下面是一个函数,可以满足您的需求。

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"