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 小时前
【C++】--AVL树的认识和实现
开发语言·数据结构·c++·算法·stl
aningxiaoxixi4 小时前
TTS 之 PYTHON库 pyttsx3
开发语言·python·语音识别
有点。4 小时前
C++ ⼀级 2023 年06 ⽉
开发语言·c++
Mr.Jessy4 小时前
JavaScript高级:深入对象与内置构造函数
开发语言·前端·javascript·ecmascript
charlie1145141914 小时前
编写INI Parser 测试完整指南 - 从零开始
开发语言·c++·笔记·学习·算法·单元测试·测试
忘记9264 小时前
session的工作原理
开发语言
java_logo4 小时前
LinuxServer.io LibreOffice 容器化部署指南
java·开发语言·docker·dubbo·openoffice·libreoffice·opensource
꧁坚持很酷꧂4 小时前
Windows安装Qt Creator5.15.2(图文详解)
开发语言·windows·qt
Alpha first5 小时前
C++核心知识点梳理:类型兼容、多继承与虚基类
开发语言·c++
.小小陈.5 小时前
C++初阶9:list使用攻略
开发语言·c++·学习·list