Lua Table的序列化与反序列化函数


Lua Table的序列化与反序列化函数
  1. table.tostring = function(t)  
  2.    local mark={}  
  3.    local assign={}  
  4.    local function ser_table(tbl,parent)  
  5.    mark[tbl]=parent  
  6.    local tmp={}  
  7.    for k,v in pairs(tbl) do  
  8.     local key= type(k)=="number" and "["..k.."]" or "[".. string.format("%q", k) .."]"  
  9.     if type(v)=="table" then  
  10.      local dotkey= parent.. key  
  11.      if mark[v] then  
  12.       table.insert(assign,dotkey.."='"..mark[v] .."'")  
  13.      else  
  14.       table.insert(tmp, key.."="..ser_table(v,dotkey))  
  15.      end  
  16.     elseif type(v) == "string" then  
  17.      table.insert(tmp, key.."=".. string.format('%q', v))  
  18.     elseif type(v) == "number" or type(v) == "boolean" then  
  19.      table.insert(tmp, key.."=".. tostring(v))  
  20.     end  
  21.    end  
  22.    return "{"..table.concat(tmp,",").."}"  
  23. end  
  24. return "do local ret="..ser_table(t,"ret")..table.concat(assign," ").." return ret end"  
  25. end  
  26.   
  27. table.loadstring = function(strData)  
  28. local f = loadstring(strData)  
  29. if f then  
  30.    return f()  
  31. end  
  32. end  

更多关于Lua的详细信息,或者下载地址请点这里

相关内容