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
+21
View File
@@ -299,4 +299,25 @@ do -- float reads: NaNs with a payload come back as the canonical NaN (LuaJIT: n
t:eq(buffer.readf64(b, 8), -2.25, "f64 normal")
end
do -- generalized iteration visits every key of sparse integer maps and arrays with holes (LuaJIT array-part borders)
local function collect(t)
local ks = {}
for k, v in t do
table.insert(ks, tostring(k) .. "=" .. tostring(v))
end
table.sort(ks)
return table.concat(ks, ",")
end
local sparse = {}
sparse[6] = "a"
sparse[7] = "b"
t:eq(collect(sparse), "6=a,7=b", "sparse integer map")
local holes = { 1, 2, 3, 4 }
holes[2] = nil
t:eq(collect(holes), "1=1,3=3,4=4", "array with a hole")
t:eq(collect({ 10, 20, 30 }), "1=10,2=20,3=30", "dense array")
t:eq(collect({ [0] = "z", "a" }), "0=z,1=a", "index 0")
t:eq(collect({ "a", x = 1 }), "1=a,x=1", "mixed")
end
t:done()