将LUA表/ json转换为KEY = VAL

时间:2016-09-27 05:01:53

标签: json lua key-value

我需要将lua表转换为KEY = VAL

e.g:

   local t1 = {
        t0 = "valt0",
        t1 = "valt1",
        tN = {
            t0key = "t0var",
            t1key = "t1var",
        }
    }

t0="valt0", t1="valt1", tN_t0key="t0var", tN_t1key="t1var"

有人有建议吗?

2 个答案:

答案 0 :(得分:0)

创建一个遍历表的函数,检查值是否为table,在这种情况下将该表反馈到同一个函数中。对于任何不是桌子的东西,把它写到你的新展平桌子上。根据发生的可能性,您可能希望通过跟踪已经迭代过的表来检查没有循环引用。

答案 1 :(得分:0)

local t1 = {
   t0 = "valt0",
   t1 = "valt1",
   t2 = 42,
   tN = {t0key = "t0var",
         t1key = "t1var"}
}

local function convert(t)
   local arr = {}
   local cyclic = {}

   local function convert_subtable(t, prefix)
      assert(not cyclic[t], 'Cannot convert: cyclic reference detected')
      cyclic[t] = true
      for k, v in pairs(t) do
         k = prefix..tostring(k)
         if type(v) == 'number' or type(v) == 'boolean' then
            table.insert(arr, k..'='..tostring(v))
         elseif type(v) == 'table' then
            convert_subtable(v, prefix..k..'_')
         else
            table.insert(arr, k..'='..string.format('%q', tostring(v)))
         end
      end
      cyclic[t] = nil
   end

   convert_subtable(t, '')
   table.sort(arr)
   return table.concat(arr, ', ')
end

print(convert(t1)) --> t0="valt0", t1="valt1", t2=42, tN_t0key="t0var", tN_t1key="t1var"