2016-09-27 23 views
-2

我需要一個Lua錶轉換爲KEY = VAL轉換LUA表/ JSON來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" 

人有什麼建議?

+0

爲什麼不簡單地使用json dump? – hjpotter92

+0

你真的需要那個輸出嗎?更好地獲取/製作一些Lua/JSON序列化器。 – FareakyGnome

+0

正如我所說:'我需要...',它是將jSON日誌轉換爲LEEF格式。 –

回答

0

創建一個循環遍歷表的函數,檢查值是否爲表,在這種情況下將該表送回到同一個函數中。對於任何不是桌子的東西,把它寫出來放到你的新的拼合桌子上。根據發生的可能性,您可能希望通過跟蹤已經迭代的表來檢查是否存在循環引用。

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"