序列化 Lua 表的方法

我可能错过了,但是有没有内置的方法可以将 Lua 表格序列化/反序列化为文本文件或者相反的操作?

我有一套方法可以对具有固定格式的 Lua 表执行此操作(例如 3 行 5 列的数据)。

有没有办法在任意任意格式的 Lua 表上执行此操作?

例如,给定以下 Lua 表:

local scenes={
    {name="scnSplash",
        obj={
            {
                name="bg",
                type="background",
                path="scnSplash_bg.png",
            },
            {
                name="bird",
                type="image",
                path="scnSplash_bird.png",
                x=0,
                y=682,
            },
        }
    },
}

它将转换为以下文本:

{name="scnSplash",obj={{name="bg",type="background",path="scnSplash_bg.png",},{name="bird",  type="image",path="scnSplash_bird.png",x=0,y=682,}},}

序列化文本的格式可以以任何方式定义,只要文本字符串可以反序列化为一个空的 Lua 表即可。

原文链接 https://stackoverflow.com/questions/9074246

点赞
stackoverflow用户161144
stackoverflow用户161144

Lua本身没有任何内置的序列化,但实现一个不难。这里列出了许多现成的实现:http://lua-users.org/wiki/TableSerialization

2012-01-31 04:20:14
stackoverflow用户909233
stackoverflow用户909233
需要 "json" 模块
定义变量 t 并将 "sample.json" 文件中的 JSON 数据解码到其中

参考[这里](https://web.archive.org/web/20150224200151/http://coronalabs.com/blog/2011/08/03/tutorial-exploring-json-usage-in-corona/)获得一个简单的JSON序列化器。
2012-01-31 05:44:02
stackoverflow用户1442917
stackoverflow用户1442917

我不确定为什么 JSON 库被标记为正确答案,因为它在序列化“带任意格式的 Lua 表”方面非常有限。它不能处理布尔值/表/函数作为键,并且不能处理循环引用。共享引用未作为共享序列化,math.huge 值在 Windows 上没有正确序列化。我意识到这些大多数是 JSON 的限制(因此在库中以这种方式实现),但这被提出作为通用 Lua 表序列化的解决方案(但实际上并不是)。

更好的选择是使用来自TableSerialization页面中的某个实现,或者使用我的Serpent序列化程序和漂亮打印程序

2012-06-13 19:14:03
stackoverflow用户511976
stackoverflow用户511976

rxi/json.lua中的json.lua添加到你的项目中,然后使用以下代码:

local json = require("json")

local encoded = json.encode({
  name = "J. Doe",
  age = 42
})

local decoded = json.decode(encoded)

print(decoded.name)

需要注意的是,如果在序列化值时存在函数,则代码会停止运行。你需要修改代码中的第82行和第93行,以跳过具有函数类型的值。

2020-09-27 10:03:16
stackoverflow用户12968803
stackoverflow用户12968803
小型解决方案:该键可以在没有括号的情况下完成,但请确保没有负号或其他特殊符号。

local nl = string.char(10) -- 换行
function serialize_list (tabl, indent)
    indent = indent and (indent.."  ") or ""
    local str = ''
    str = str .. indent.."{"..nl
    for key, value in pairs (tabl) do
        local pr = (type(key)=="string") and ('["'..key..'"]=') or ""
        if type (value) == "table" then
            str = str..pr..serialize_list (value, indent)
        elseif type (value) == "string" then
            str = str..indent..pr..'"'..tostring(value)..'",'..nl
        else
            str = str..indent..pr..tostring(value)..','..nl
        end
    end
    str = str .. indent.."},"..nl
    return str
end

local str = serialize_list(tables)
print(str)
2021-01-08 09:02:50