lua排序序列化时只需传入obj的值,直接获取table的数据进行遍历 lua排序序列化时只需传入obj的值,直接获取table的数据进行遍历

lua排序序列化时只需传入obj的值,直接获取table的数据进行遍历

-- 序列化
-- 序列化时只需传入obj的值,其它保持nil
function serialize(obj, name, newline, depth)
    local space = newline and "    " or ""
    newline = newline and true
    depth = depth or 0
    if depth > 10 then
        return "..."
    end
    local tmp = string.rep(space, depth)

    if name then
        if type(name) == "number" then
            tmp = tmp .. "[" .. name .. "] = "
        else
            tmp = tmp .. tostring(name) .. " = "
        end
    end

    if type(obj) == "table" then
        tmp = tmp .. "{" .. (newline and "\n" or "")

        for k, v in pairs(obj) do
            tmp =  tmp .. serialize(v, k, newline, depth + 1) .. "," .. (newline and "\n" or "")
        end

        tmp = tmp .. string.rep(space, depth) .. "}"
    elseif type(obj) == "number" then
        tmp = tmp .. tostring(obj)
    elseif type(obj) == "string" then
        tmp = tmp .. string.format("%q", obj)
    elseif type(obj) == "boolean" then
        tmp = tmp .. (obj and "true" or "false")
    elseif type(obj) == "function" then
        -- tmp = tmp .. tostring(obj)
        tmp = tmp .. "\"【function】\""
    elseif type(obj) == "userdata" then
        tmp = tmp .. "\"【userdata】\""
    else
        tmp = tmp .. "\"[" .. string.format("%s", tostring(obj)) .. "]\""
    end

    return tmp
end


-- for i in pairs(skillgroup) do
--     print("直接输出:"..i)
-- end
-- -- 直接获取table的数据进行遍历发现数据不像list那样是直接索引取出排序好的,下面进行排序
-- -- 插入key
-- local keyTest ={}
-- for i in pairs(skillgroup) do
--    table.insert(keyTest,i)  
-- end
-- -- 对key进行升序
-- table.sort(keyTest,function(a,b)return (tonumber(a) <  tonumber(b)) end)  
-- --对key进行降序
-- table.sort(keyTest,function(a,b)return (tonumber(a) >  tonumber(b)) end)  
-- -- 结果数据
-- local result = { }
-- for i,v in pairs(keyTest) do
--    table.insert(result,skillgroup[v])
--     print("id:"..v.."     data:"..skillgroup[v].SkillGroupID)
-- end

评论 0

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论