lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2015-01-29 14:13 GMT+00:00 Tony Papadimitriou <tonyp@acm.org>:
> I’m looking for the best (?) general way to implement *nested* iterators in
> Lua (5.3, of course).
>
> For example:  I have an iterator that returns single items when used in a
> FOR .. IN loop.  Each item is treated somehow but that loop, and the result
> I want it to become available in another iterator.
>
> Easy, but I do NOT want to store all intermediate results in a table, and
> then traverse the table again, as the size of the table could be too large
> or even unknown while the iterator is running (until some condition happens
> that terminates it).
>
> In Python 3, for example, this would be very simple with each routine using
> YIELD instead of RETURN, and iterators can be nested to an arbitrary level.
> But, in Lua, I can’t seem to find an obvious (memory efficient) solution.
> (I would love for Lua to have the same simplicity in this regard.)
>
> Perhaps explicit use of co-routines is one solution, but maybe there is a
> more immediate way I missed.
>
> Maybe someone can point me to some example.

You can use coroutine.yield like in Python, and use coroutine.wrap to
create coroutines easily. For example:

local yield,wrap = coroutine.yield,coroutine.wrap

local function integers(count)
    for i=1,count do
        yield(i)
    end
end

local function evens(count)
    for i in wrap(integers), count do
        yield(i * 2)
    end
end

local function odds(count)
    for i in wrap(evens), count do
        yield(i + 1)
    end
end

for i in wrap(odds), 12 do
    print(i)
end

Short of custom language modification I can't imagine any simpler syntax.