lua-users home
lua-l archive

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

> The Lua5 manual begins its definition of coroutines this way:

>      Lua supports coroutines, also called semi-coroutines, generators, or
>      colaborative multithreading.

> And describes the new "for" syntax this way:

>      The generic for statement works over functions, called generators.
>      calls its generator to produce a new value for each iteration,
>     stopping when the new value is nil.


Lua does not call coroutines "generators" but in the world at large
are also called "generators".

Lua calls functinos used in the generic for statement "generators"

I admit that the documentation could be improved, but I think it is
technically accurate.

> And how do iterators control their state if they don't control when they
> yield...?

They stash it somewhere, quite possibly in a closure.

> > I am passing this one as I don't know what this "wrap" is about.

> I gave examples like:

>      withOutputToFile() do
>            -- write stuff
>      end

> with the implementation:

>      function withOutputToFile( file )
>            writeto( file )
>            yield()
>            writeto()
>      end

> This doesn't yield any value, it just "wraps" the call to the
> is really just an anonymous function.

> This idiom is useful anytime resources must be protected.

You could do this with a carefully crafted for-generator. The
implementation is left as an exercise to the reader.