Skip to content

Commit a4d36b8

Browse files
committed
Fix deepcompare with __pairs
This uses `next, t` instead of `pairs(t)` to iterate through a table so that the `__pairs` metamethod is not used.
1 parent d63fbb7 commit a4d36b8

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

spec/assertions_spec.lua

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,13 @@ describe("Test Assertions", function()
4545
assert.is_not.same(nil, "a string")
4646
end)
4747

48+
it("Checks same() assertion ignores __pairs metamethod", function()
49+
local t1 = setmetatable({1,2,3}, {__pairs = function(t) return nil end})
50+
local t2 = {1,2,3}
51+
assert.same(t1, t2)
52+
assert.same(t2, t1)
53+
end)
54+
4855
it("Checks same() assertion to handle recursive tables", function()
4956
local t1 = { k1 = 1, k2 = 2 }
5057
local t2 = { k1 = 1, k2 = 2 }

src/util.lua

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ function util.deepcompare(t1,t2,ignore_mt,cycles,thresh1,thresh2)
3030
cycles[1][t1] = cycles[1][t1] + 1
3131
cycles[2][t2] = cycles[2][t2] + 1
3232

33-
for k1,v1 in pairs(t1) do
33+
for k1,v1 in next, t1 do
3434
local v2 = t2[k1]
3535
if v2 == nil then
3636
return false, {k1}
@@ -43,7 +43,7 @@ function util.deepcompare(t1,t2,ignore_mt,cycles,thresh1,thresh2)
4343
return false, crumbs
4444
end
4545
end
46-
for k2,_ in pairs(t2) do
46+
for k2,_ in next, t2 do
4747
-- only check wether each element has a t1 counterpart, actual comparison
4848
-- has been done in first loop above
4949
if t1[k2] == nil then return false, {k2} end
@@ -58,7 +58,7 @@ end
5858
function util.shallowcopy(t)
5959
if type(t) ~= "table" then return t end
6060
local copy = {}
61-
for k,v in next, t, nil do
61+
for k,v in next, t do
6262
copy[k] = v
6363
end
6464
return copy
@@ -74,7 +74,7 @@ function util.deepcopy(t, deepmt, cache)
7474
if cache[t] then return cache[t] end
7575
cache[t] = copy
7676

77-
for k,v in next, t, nil do
77+
for k,v in next, t do
7878
copy[k] = (spy.is_spy(v) and v or util.deepcopy(v, deepmt, cache))
7979
end
8080
if deepmt then

0 commit comments

Comments
 (0)