new primitive for iterating partially over an array
This commit is contained in:
parent
d7415b95f6
commit
040c9dfefc
18
array.lua
18
array.lua
|
@ -26,3 +26,21 @@ function array.any(arr, f)
|
||||||
end
|
end
|
||||||
return false
|
return false
|
||||||
end
|
end
|
||||||
|
|
||||||
|
-- like ipairs, but support an index to start iterating from
|
||||||
|
-- idx is inclusive; the first call to the iterator will return idx
|
||||||
|
function array.each(arr, idx)
|
||||||
|
if idx then
|
||||||
|
if type(idx) ~= 'number' then
|
||||||
|
error("argument #2 to 'array.each' must be an integer if provided")
|
||||||
|
end
|
||||||
|
assert(idx >= 1, ("can't start iterating over an array from %d; the starting index needs to be at least 1"):format(idx))
|
||||||
|
end
|
||||||
|
idx = idx and idx-1 or 0
|
||||||
|
local iter = ipairs(arr)
|
||||||
|
return function()
|
||||||
|
local elem
|
||||||
|
idx, elem = iter(arr, idx)
|
||||||
|
return idx, elem
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
Loading…
Reference in New Issue