lua中判断2个表是否相等

当我们获取 table 长度的时候无论是使用 **#**还是 table.getn其都会在索引中断的地方停止计数,而导致无法正确取得 table 的长度,而且还会出现奇怪的现象。例如:t里面有3个元素,但是因为最后一个下表是5和4,却表现出不一样的长度。

所以通常准确计算table的长度就是通过pairs来遍历(ipairs只能针对从数字1开始的连续索引,碰到不是数字或者不连续的就停止遍历

Lua 复制代码
local function getTableLength(t)
    local length=0
    for k,v in pairs(t) do
        length = length+1
    end
    return length
end

local function isEqualTable(tab1,tab2)
    local typer1,typer2 = type(tab1),type(tab2)
    if "table"~=typer1 and "table"~=typer2 then return tab1==tab2 end
    if "table"==typer1 and "table"~=typer2 then return false end
    if "table"~=typer1 and "table"==typer2 then return false end
    if tab1 == tab2 then return true end
    if getTableLength(tab1) ~= getTableLength(tab2) then return false end
    for k,v in pairs(tab1) do
        local tmp = tab2[k]
        return isEqualTable(v,tmp)
    end
    return true
end
Lua 复制代码
local t1 = {a = 1, b = 2}
local t2 = {b = 2, a = 1}

local t3 = {a = 1, b = 2, c = 3}

local t7={"a","b",c={{a = 1, b = 2}}}
local t8={"a","b",c={{b = 2, a = 1}}}

print(isEqualTable(t1, t2)) -- 输出: true
print(isEqualTable(t1, t3)) -- 输出: false
print(isEqualTable(t7, t8)) -- 输出: true
相关推荐
铁东博客3 分钟前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui4 分钟前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳6 分钟前
Python从入门到精通day63
开发语言·python
lbb 小魔仙6 分钟前
Python_RAG知识库问答系统实战指南
开发语言·python
551只玄猫1 小时前
【数学建模 matlab 实验报告13】主成分分析
开发语言·数学建模·matlab·课程设计·主成分分析
zzzzls~2 小时前
Python 工程化: 用 Copier 打造“自我进化“的项目脚手架
开发语言·python·copier
韶博雅2 小时前
emcc24ai
开发语言·数据库·python
yongui478342 小时前
C# 与三菱PLC通讯解决方案
开发语言·c#
2501_933329552 小时前
技术架构深度解析:Infoseek舆情监测系统的全链路设计与GEO时代的技术实践
开发语言·人工智能·分布式·架构
Tong Z2 小时前
常见的限流算法和实现原理
java·开发语言