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 -- Localize globals
local error, coroutine, modlib, unpack, select, setmetatable local modlib, unpack, select, setmetatable
= error, coroutine, modlib, unpack, select, setmetatable = modlib, unpack, select, setmetatable
-- Set environment -- Set environment
local _ENV = {} local _ENV = {}
@ -49,28 +49,6 @@ function memoize(func)
}) })
end 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 -- Does not use select magic, stops at the first nil value
function aggregate(binary_func, total, ...) function aggregate(binary_func, total, ...)
if total == nil then return end 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 local add = modlib.func.add
--+ For all functions which aggregate over single values, use modlib.table.ivalues - not ipairs - for lists! --+ 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, ...)) return loop(iterator(state, ...))
end 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) function iterator.range(from, to, step)
if not step then if not step then
if not to then if not to then