首页 > 代码库 > lua 对表的简单序列化与反序列化

lua 对表的简单序列化与反序列化

参考文档:http://blog.csdn.net/xiaodan007/article/details/7096718

function sz_T2S(_t)
    local szRet = "{"
    function doT2S(_i, _v)
        if "number" == type(_i) then
            szRet = szRet .. "[" .. _i .. "] = "
            if "number" == type(_v) then
                szRet = szRet .. _v .. ","
            elseif "string" == type(_v) then
                szRet = szRet .. " .. _v .. " .. ","
            elseif "table" == type(_v) then
                szRet = szRet .. sz_T2S(_v) .. ","
            else
                szRet = szRet .. "nil,"
            end
        elseif "string" == type(_i) then
            szRet = szRet .. [" .. _i .. "] = 
            if "number" == type(_v) then
                szRet = szRet .. _v .. ","
            elseif "string" == type(_v) then
                szRet = szRet .. " .. _v .. " .. ","
            elseif "table" == type(_v) then
                szRet = szRet .. sz_T2S(_v) .. ","
            else
                szRet = szRet .. "nil,"
            end
        end
    end
    table.foreach(_t, doT2S)
    szRet = szRet .. "}"
    return szRet
end

function unsz_S2T(str)
    str = "return " .. str;
    local fun = loadstring(str);
    return fun();
end

local tt = {}
tt[1] = "aa";
tt.name = "halldd";
tt.tt = {};
tt.tt[3] = "bb";
print (tt[1]);

local ss = sz_T2S(tt);
local ttv = unsz_S2T(ss);
print (tt.name, tt.tt[3]);