我需要进行比较,看看两个表是否相同 – 就像在相同的内容中一样.两个表都有表作为键. 例如: t1 = {{1,1},{2,2}}t2 = {{1,1},{2,2}}t3 = {{1,1},{2,2},{3,3}} t1和t2应该相等,但t1和t3不应该相等. 我的解
例如:
t1 = {{1,1},{2,2}} t2 = {{1,1},{2,2}} t3 = {{1,1},{2,2},{3,3}}
t1和t2应该相等,但t1和t3不应该相等.
我的解决方案不是绝对的(不喜欢键),但应该使用您提出问题的嵌套表.我的概念是递归和简单的:从每个输入中获取一个条目,确保它们:匹配类型,两个都是表,并且两个表的长度相同.如果这三件事都成立,你现在可以1:1递归地比较两个表.如果类型不匹配或表的长度不同,则表示自动失败.
function compare (one, two) if type(one) == type(two) then if type(one) == "table" then if #one == #two then -- If both types are the same, both are tables and -- the tables are the same size, recurse through each -- table entry. for loop=1, #one do if compare (one[loop], two[loop]) == false then return false end end -- All table contents match return true end else -- Values are not tables but matching types. Compare -- them and return if they match return one == two end end return false end do t1 = {{1,1},{2,2}} t2 = {{1,1},{2,2}} t3 = {{1,1},{2,2},{3,3}} print (string.format( "t1 == t2 : %s", tostring(compare (t1,t2)))) print (string.format( "t1 == t3 : %s", tostring(compare (t1,t3)))) end
输出是:
t1 == t2 : true t1 == t3 : false