Last active
February 15, 2023 13:26
-
-
Save outsinre/1e93db29cdd653b2546a9700eb2890b3 to your computer and use it in GitHub Desktop.
Lua gist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- deeply compare two objects like 'pl.tablex.deepcompare()' | |
local function deep_equals(t1, t2, ignore_mt) | |
-- different type | |
if t1Type ~= t2Type then return false end | |
-- compare simple values directly | |
if t1Type ~= 'table' then return t1 == t2 end | |
-- both table type; try metatable method | |
if not ignore_mt then | |
local mt1 = getmetatable(t1) | |
if mt1 and mt1.__eq then | |
--compare using built in method | |
return t1 == t2 | |
end | |
end | |
-- without metatable method or ignore metatable | |
-- iterate over t1 | |
for key1, value1 in pairs(t1) do | |
local value2 = t2[key1] | |
if value2 == nil or deep_equals(value1, value2, ignore_mt) == false then | |
return false | |
end | |
end | |
-- check keys in t2 but missing from t1 | |
for key2, _ in pairs(t2) do | |
if t1[key2] == nil then return false end | |
end | |
return true | |
end | |
-- example | |
local t1 = { { 1 }, { 2 }, { 3 } }; local t2 = { { 3 }, { 2 }, { 1 } } | |
if deep_equals(t1, t2, true) then | |
print("yes") | |
else | |
print("no") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment