Move for_generator from func.* to iterator.*

This commit is contained in:
Lars Mueller 2022-09-07 12:00:32 +02:00
parent 6d527b0471
commit 5e7c29980d
2 changed files with 26 additions and 24 deletions

@ -1,6 +1,6 @@
-- Localize globals
local error, coroutine, modlib, unpack, select, setmetatable
= error, coroutine, modlib, unpack, select, setmetatable
local modlib, unpack, select, setmetatable
= modlib, unpack, select, setmetatable
-- Set environment
local _ENV = {}
@ -49,28 +49,6 @@ function memoize(func)
})
end
function for_generator(caller, ...)
local co = coroutine.create(function(...)
return caller(function(...)
return coroutine.yield(...)
end, ...)
end)
local args = {...}
return function()
if coroutine.status(co) == "dead" then
return
end
local function _iterate(status, ...)
if not status then
error((...))
end
return ...
end
return _iterate(coroutine.resume(co, unpack(args)))
end
end
-- Does not use select magic, stops at the first nil value
function aggregate(binary_func, total, ...)
if total == nil then return end

@ -1,3 +1,6 @@
local coroutine_create, coroutine_resume, coroutine_yield, coroutine_status, unpack
= coroutine.create, coroutine.resume, coroutine.yield, coroutine.status, unpack
local add = modlib.func.add
--+ For all functions which aggregate over single values, use modlib.table.ivalues - not ipairs - for lists!
@ -14,6 +17,27 @@ function iterator.foreach(callback, iterator, state, ...)
return loop(iterator(state, ...))
end
function iterator.for_generator(caller, ...)
local co = coroutine_create(function(...)
return caller(function(...)
return coroutine_yield(...)
end, ...)
end)
local args = {...}
return function()
if coroutine_status(co) == "dead" then
return
end
local function _iterate(status, ...)
if not status then
error((...))
end
return ...
end
return _iterate(coroutine_resume(co, unpack(args)))
end
end
function iterator.range(from, to, step)
if not step then
if not to then