lua-users home
lua-l archive

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


> 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...?

Hang on--I think I see what they're doing:

      A for statement like

            for var_1, ..., var_n in explist do block end

      is equivalent to the code:

            do
                  local _f, _s, var_1, ..., var_n = explist
                  while 1 do
                        var_1, ..., var_n = _f(_s, var_1)
                        if var_1 == nil then break end
                        block
                  end
            end

In effect, it looks like vars are popped onto the stack and passed *back
into* the "generator." That's how the generator maintains state. So I think
I was confused because the documentation uses "generator" to describe two
different things...

Ok, I'll have to think about this a bit more. I think my suggestion still
stands, though, as a way to make the use of anonymous functions "more
natural"--and that in turn leads to what I think is a more natural
implementation of iterators. (Indeed, you no longer need this special "for"
syntax--and it becomes easy to implement a "withOutputToFile" that *feels*
right.)