fix hardcoded call to pairs, add test

develop
myk002 2021-08-20 22:55:07 -07:00
parent 119595dcaf
commit 86b2329b7f
No known key found for this signature in database
GPG Key ID: 8A39CA0FA0C16E78
2 changed files with 17 additions and 1 deletions

@ -175,7 +175,7 @@ end
function safe_pairs(t, iterator_fn) function safe_pairs(t, iterator_fn)
iterator_fn = iterator_fn or pairs iterator_fn = iterator_fn or pairs
if (pcall(pairs, t)) then if (pcall(iterator_fn, t)) then
return _wrap_iterator(iterator_fn(t)) return _wrap_iterator(iterator_fn(t))
else else
return function() end return function() end

@ -22,3 +22,19 @@ function test.safe_pairs()
end end
expect.eq(3, iterated) expect.eq(3, iterated)
end end
function test.safe_pairs_ipairs()
local t = {1, 2}
setmetatable(t, {
__pairs = function()
expect.fail('pairs() should not be called')
end,
})
local iterated = 0
for k,v in safe_pairs(t, ipairs) do
expect.eq(k, v)
iterated = iterated + 1
end
expect.eq(#t, iterated)
end