保存不带循环的表
function serialize (o)
local t = type(o)
if t == "number " or t == "string" or t == "boolean" or t == "nil" then
io.write(string.format("q", o))
elseif t == "table" then
io.write("{\n")
for k, v in pairs(o) do
io.write(" ", k , " = ")
serialize(v)
io.write(",\n")
end
io.write("}\n")
else
error("cannot serialize a ".. type(o))
end
end
上述函数只要表结构式一棵树而非图(即没有共享的子表和环),那么函数也可以处理嵌套的表。
serialize{a=12, b = 'Lua', key = 'another "one"'}
{
a = 12,
b = "Lua"
key = "another \"one\""
}
保存带有循环的表
由于表构造器不能创建带有循环的或共享子表的表,如果要处理表示通用拓扑结构的表,就需要采用不同的方法。
function basicSerialize (o)
return string.format("%q", o)
end
function save (name, value, saved)
saved = saved or {}
io.write(name, " = ")
if type(value) == "table" then
if saved[value] then
io.write(saved[value], "\n")
else
saved[value] = name
io.write("{}\n")
for k,v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
save(fname, v, saved)
end
end
else
error("cannot save a" .. type(value))
end