1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| function (t) local mark = {} local assign = {} local function serialize(tbl, parent) mark[tbl] = parent local tmp = {} for k, v in pairs(tbl) do local typek = type(k) local typev = type(v)
local key = typek == "number" and "[" .. k .."]" or k
if typev == "table" then local dotkey = parent .. (typek == "number" and key or "." .. key) if mark[v] then table.insert(assign, dotkey .. "=" .. mark[v]) else if typek == "number" then table.insert(tmp, serialize(v,dotkey)) else table.insert(tmp, key .. "=" .. serialize(v, dotkey)) end end else if typev == "string" then v = string.gsub(v, "n", "\n") if string.match( string.gsub(v,"[^'"]",""), '^"+$' ) then v = "'" .. v .. "'" else v = '"' .. v .. '"' end else v = tostring(v) end
if typek == "number" then table.insert(tmp, v) else table.insert(tmp, key .. "=" .. v) end end end return "{" .. table.concat(tmp, ",") .. "}" end return serialize(t, "ret") .. table.concat(assign," ") end
function table.loadstring(str) local chunk = loadstring("do local ret = " .. str .. " return ret end") if chunk then return chunk() end end
|