compat: __iter walks 1..#t skipping holes (sparse integer maps / arrays with holes visited fully on LuaJIT, as in Luau)

This commit is contained in:
4DBug committed 2026-10-31 09:56:39 -05:00
1 parent 17c00a15df
commit 08ea206447
2 files changed
+37 -1

No files matched your search

+16 -1
View File
@@ -404,13 +404,28 @@ do
end
-- ---------------------------------------------------------------------------------------------------- __iter
local function arrayIter(s, i)
local t, n = s[1], s[2]
i = i + 1
local v = t[i]
while v == nil and i < n do
i = i + 1
v = t[i]
end
if v ~= nil then return i, v end
end
function M.__iter(t, s, c)
if rawtype(t) == "function" then return t, s, c end
if rawtype(t) ~= "table" then error("attempt to iterate over a " .. M.type(t) .. " value", 2) end
local mt = getmetatable(t)
if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end
local n = #t
if n > 0 and t[0] == nil and next(t, n) == nil then return ipairs(t) end -- LuaJIT keeps t[0] in the array part
-- every key is an integer in 1..n (next(t, n) == nil: nothing after n in the array part, an empty hash part;
-- LuaJIT keeps t[0] in the array part, so check it): walk 1..n skipping holes. #t is any border, so sparse maps
-- such as {[6] = a, [7] = b} (n = 7, t[1] == nil) and arrays with holes visit every key, as in Luau.
if n > 0 and t[0] == nil and next(t, n) == nil then
return arrayIter, { t, n }, 0
end
return next, t, nil
end