LUA
LUA中table和字符串相互转换
有时会遇到需要将一个table保存起来或传递给另一个string中的时候,table的序列化和反序列化就起到作用了。
需要使用到一个辅助函数
function ToStringEx(value) if type(value)=='table' then return TableToStr(value) elseif type(value)=='string' then return "\'"..value.."\'" else return tostring(value) end end
Table To String
function TableToStr(t) if t == nil then return "" end local retstr= "{" local i = 1 for key,value in pairs(t) do local signal = "," if i==1 then signal = "" end if key == i then retstr = retstr..signal..ToStringEx(value) else if type(key)=='number' or type(key) == 'string' then retstr = retstr..signal..'['..ToStringEx(key).."]="..ToStringEx(value) else if type(key)=='userdata' then retstr = retstr..signal.."*s"..TableToStr(getmetatable(key)).."*e".."="..ToStringEx(value) else retstr = retstr..signal..key.."="..ToStringEx(value) end end end i = i+1 end retstr = retstr.."}" return retstr end
String To Table
function StrToTable(str) if str == nil or type(str) ~= "string" then return end --loadstring 已经弃用 return load("return " .. str)() end
测试结果
local t1 = {A=1, B={1, b="strBb", {x='strB2x', y=0.1} } } print(t1.B[2].x)
-- strB2x local str1 = TableToStr(t1) print(str1)
-- {['A']=1,['B']={1,{['y']=0.1,['x']='strB2x'},['b']='strBb'}} local t2 = StrToTable(str1) print(t2['B'][2].x)
-- strB2x