diff --git a/func.lua b/func.lua index 70c2178..da9d601 100644 --- a/func.lua +++ b/func.lua @@ -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 diff --git a/iterator.lua b/iterator.lua index fdab8de..ac6f0e1 100644 --- a/iterator.lua +++ b/iterator.lua @@ -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