function(t) local mark = {} local assign = {} localfunctionserialize(tbl, parent) mark[tbl] = parent local tmp = {} for k, v inpairs(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") ifstring.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
functiontable.loadstring(str) local chunk = loadstring("do local ret = " .. str .. " return ret end") if chunk then return chunk() end end
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
local t = {a = 1, b = 2} t.rt = {c = 3, d = 4, t}
local s = table.tostring(t) print(s)
local tl = table.loadstring(s) assert(tl.a == t.a)
----------------------------------------------
local t = {['foo']='bar', 11, 22, 33, "ss"aa"bbncc", "hello", {'a','b'}}
local s = table.tostring(t) print(s) -- 输出 {11,22,33,'ss"aa"bbncc',"hello",{"a","b"},foo="bar"}
local tl = table.loadstring(s) assert(tl.foo == t.foo) assert(tl[4] == 'ss"aa"bbncc')