[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Coroutines & Iterators
- From: RLake@...
- Date: Wed, 8 Jan 2003 13:01:06 -0500
> 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.
It
> calls its generator to produce a new value for each iteration,
> stopping when the new value is nil.
<<SNIP>>
Lua does not call coroutines "generators" but in the world at large
coroutines
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
block--which
> 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.
R.