将Lua字符串拆分为带子表的表

时间:2015-09-29 00:35:26

标签: lua string-matching lua-table

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

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

生成表格
x = {
  y = {
    z = {
    }
  }
}

1 个答案:

答案 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"