Skip to content

Instantly share code, notes, and snippets.

@yunyyyun
Created May 27, 2017 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yunyyyun/f69413fbb17c79d88afe773414bc6bcb to your computer and use it in GitHub Desktop.
Save yunyyyun/f69413fbb17c79d88afe773414bc6bcb to your computer and use it in GitHub Desktop.
把table转string,字符串结果可直接反过来load成table
table.tostring = function(t)
if t==nil then
return "error,print table is nil!"
end
local assign={}
local function ser_table(tbl,parent)
local tmp={}
for k,v in pairs(tbl) do
local key= type(k)=="number" and "["..k.."]" or "[".. string.format("%q", k) .."]"
if type(v)=="table" then
local dotkey= parent.. key
table.insert(tmp, key.."="..ser_table(v,dotkey))
elseif type(v) == "string" then
table.insert(tmp, key.."=".. string.format('%q', v))
elseif type(v) == "number" or type(v) == "boolean" then
table.insert(tmp, key.."=".. tostring(v))
elseif type(v) == "function" then
table.insert(tmp, key.."= function")
end
end
return "{"..table.concat(tmp,",").."}"
end
return "do local ret="..ser_table(t,"ret")..table.concat(assign," ").." return ret end"
end
table.loadstring = function(strData)
local f,errormsg = loadstring(strData)
if f then
return f()
else
local logMsg="解析数据为:"..type(strData).. " ".. strData.. " 错误信息为:".. errormsg;
LogMessage(logMsg);
end
end
local otb = {["foo"]="bar"}
local tb0 = {}
tb0["origin"]=otb
tb0["zq"]=tb0["origin"]
local tbStr = table.tostring(tb0)
print("tb0==",tbStr)
local tb1 = table.loadstring(tbStr)
print("tb1==",table.tostring(tb1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment