@ -175,7 +175,7 @@ end
function safe_pairs(t, iterator_fn)
iterator_fn = iterator_fn or pairs
if (pcall(pairs, t)) then
if (pcall(iterator_fn, t)) then
return _wrap_iterator(iterator_fn(t))
else
return function() end
@ -22,3 +22,19 @@ function test.safe_pairs()
end
expect.eq(3, iterated)
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
expect.eq(#t, iterated)