比较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

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...