lua-users home
lua-l archive

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


> Why would anyone assume that coroutines have something to do with
> iterators beats the life out of me.
> ...
> But to say as much as
>
>     "It seems like Lua5 is headed toward using coroutines for iterators."
>
> seems a bit too much.

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.

And describes the new "pairs()" function this way:

      Returns the function next and the table t, so that the construction
            for k,v in pairs(t) do ... end
      will iterate over all pairs of key--value of table t.

And under the "incompatibilities" section says:

      The old construction for k,v in t, where t is a table, is deprecated
      (although it is still supported). Use for k,v in pairs(t) instead.

So that's why I think that Lua5 is headed toward using coroutines for
iterators.

And they're not the only reasons. For example, there's no "yield" statement
in
the language. The only way to yield values is through coroutine.yield, etc.
And
how do iterators control their state if they don't control when they
yield...?

Granted, I might be wrong--but there's lots of reason to form this opinion.

Perhaps one of the Lua5 authors could clarify.

>> * third, it implies (by using the suggestive "for ... in ..." phrasing)
>>  iteration--but you don't always want to iterate, sometimes you just
want to
>>  "wrap".
>>
> 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.