我需要进行比较,看看两个表是否相同 – 就像在相同的内容中一样.两个表都有表作为键.
例如:
t1 = {{1,1},{2,2}} t2 = {{1,2}} t3 = {{1,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,2}} t2 = {{1,2}} t3 = {{1,3}} print (string.format( "t1 == t2 : %s",tostring(compare (t1,t2)))) print (string.format( "t1 == t3 : %s",t3)))) end
输出是:
t1 == t2 : true t1 == t3 : false
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。