比较lua中的表,其中键是表

前端之家收集整理的这篇文章主要介绍了比较lua中的表,其中键是表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要进行比较,看看两个表是否相同 – 就像在相同的内容中一样.两个表都有表作为键.

例如:

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

猜你在找的Lua相关文章