lua-users home
lua-l archive

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


Your stateful function is wrong. It's stateful because the iterator keeps a 
private state. This means the third value, the initial state, is not used. The 
version you wrote will be invoked with i=0 the first time, then i=min, then 
i=min+min, etc.

Fixed version is:

> --stateful
> --[[
> function fromto(n,m)
>   local r = m - n
>   local i = -1
>   return function()
>     i = i + 1
>     if i < r then
>       return n + i
>     else
>       return nil
>     end
>   end
> end
> --]]

Your stateless iterator is correct. The function receives the state variable 
from the invoker which it mutates then passes back. Each time the iterator 
receives the result of the previous iteration, which is suitable when each 
element in the sequence is derived from the previous element. If you need more 
state than what the iterator returns, you need to be stateful. For instance, 
you couldn't generate a Fibonacci sequence with a stateless iterator. No, 
that's not true. But it would look like:

for _,n in fibonacci() do print(n) end

Where _ is a table or closure. But if you're going to create the garbage 
anyway, you may as well make the iterator a closure.

-- 
tom <telliamed@whoopdedo.org>