Lua:如何将字符串反序列化为多维表?

我目前卡在这个函数上: 我有一个函数,它接受一个多维表并将其转换为字符串。格式与Lua代码中的表格相同。 现在我需要反转它-目标是获得相同的多维表。 我已经找到了从表格获取字符串的函数-相反的函数会是什么?

    toReturn = "{"
    for ind, val in pairs(tbl) do
        if type(val) == "table" then
            toReturn = toReturn .. (type(ind) == "number" and "" or ind .. "=") .. tableAsString(val) .. ","
        else
            local newVal
            if type(val) == "string" then
                newVal = "\"" .. val .. "\""
            else
                newVal = val
            end
            toReturn = toReturn .. (type(ind) == "number" and "" or ind .. "=") .. newVal .. ","
        end
    end

    toReturn = toReturn:sub(1,-2) .. "}" -- 删除尾随的","并关闭表格

    return toReturn
end
点赞
用户9132683
用户9132683

Nifim's答案非常完美,我的问题已经解决了。

可以使用以下代码读取表格:

loadstring(serializedTable)()

再次感谢!

2020-01-13 22:02:08
用户4515989
用户4515989

你的表格可能包含字符串,其中包含字符串",换行符,制表符等。我为自己编写了此函数来处理:

local function buildLiteral(value, tableAsVararg, buildedLiteralsCache)
    if not buildedLiteralsCache then
        buildedLiteralsCache = {}
    end

    local resultStr = nil

    if value == nil then
        resultStr = "nil"
    else
        if not buildedLiteralsCache[value] then
            local t = type(value)
            local str = nil

            if t == "boolean" or t == "number" then
                str = tostring(value)
            elseif t == "string" then
                str = "\"" .. string.gsub(string.gsub(string.gsub(string.gsub(string.gsub(value, "\\", "\\\\"), "\"", "\\\""), "\r", "\\r"), "\n", "\\n"), "\t", "\\t") .. "\""
            elseif t == "table" then
                if tableAsVararg then
                    str = ""

                    if table.getn(value) >= 1 then
                        for _, v in ipairs(value) do
                            str = str .. buildLiteral(v, false, buildedLiteralsCache) .. ", "
                        end

                        str = string.sub(str, 1, string.len(str) - 2)
                    end
                else
                    str = "{"

                    for k, v in pairs(value) do
                        str = str .. "[" .. buildLiteral(k, false, buildedLiteralsCache) .. "]=" .. buildLiteral(v, false, buildedLiteralsCache) .. ", "
                    end

                    if string.len(str) > 1 then
                        str = string.sub(str, 1, string.len(str) - 2)
                    end

                    str = str .. "}"
                end
            else
                error("buildLiteral called with unsupported type='" .. t .. "'")
            end

            buildedLiteralsCache[value] = str
        end

        resultStr = buildedLiteralsCache[value]
    end

    return resultStr
end

您可以使用loadstring(str)()再次加载表格。

2020-01-14 15:34:31