另一种方法是以shown in Programming in Lua 的方式序列化两个表。这将生成一个字符串集合的输出,在运行时将重新创建表。将序列化器的输出存储在一个表中,而不是输出它们进行比较。
一旦两个表都被序列化为字符串集合,就可以简单地将序列化表 A 中的所有行与序列化表 B 中的所有行进行比较,并删除它们之间的任何重复项。如果在处理表 A 的末尾,表 A 或表 B 中还有任何行,则它们不相等。
序列化为字符串表的代码(从 PIL 修改)并比较两个表 a 和 b:
function basicSerialize (o)
if type(o) == "number" then
return tostring(o)
else -- assume it is a string
return string.format("%q", o)
end
end
function save (name, value, saved, output)
saved = saved or {} -- initial value
output = output or {} -- initial value
if type(value) == "number" or type(value) == "string" then
table.insert (output, name .. " = " .. basicSerialize(value))
elseif type(value) == "table" then
if saved[value] then -- value already saved?
table.insert (output, name .. " = " .. saved[value]) -- use its previous name
else
saved [value] = name -- save name for next time
table.insert (output, name .. " = {}") -- create a new table
for k,v in pairs(value) do -- save its fields
local fieldname = string.format("%s[%s]", name, basicSerialize(k))
save (fieldname, v, saved, output)
end
end
else
error("cannot save a " .. type(value))
end
return output
end
function compareSerializedTable (t1, t2)
if (#t1 ~= #t2) then
return false
end
for i = #t1, 1, -1 do
local line = t1 [i]
for k, comp in ipairs (t2) do
if (line == comp) then
table.remove (t1, i)
table.remove (t2, k)
break
end
end
end
return (#t1 == 0 and #t2 == 0)
end
t1 = {{1,1},{2,2}}
t2 = {{1,1},{2,2}}
t3 = {{1,1},{2,2},{3,3}}
o1 = save ('t', t1)
o2 = save ('t', t2)
o3 = save ('t', t3)
print (compareSerializedTable (o1, o2)) --true
print (compareSerializedTable (o1, o3)) --false