lua-users home
lua-l archive

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


<astient@laposte.net> writes:

> I'm stuck in my understanding of the way an iterator works. I found
> already some explanations in the lua doc but I don't understand why
> when calling a function by the "in" command the behavior of the
> variable in the function is different (ie: defined as local but
> behaves as global) :
>
> ----------------------------------------------------------- 
> local table={1,2,3} 
>
> function iterator(table) 
> local y = 0 
> return function() y=y+1 print(y) return table[y] end 
> end 
>
> -- 1) function iterator called by "for": 
>
> for i = 1,3 do 
> iterator(table)() 
> end 
>
> -- 2) function iterator call by "in": 
>
> for i in iterator(table) do end 
> ------------------------------------------------------------- 
>
> The 2 loops call the same function, but in the first case the local
> variable y is not retained (which is the normal behavior of local
> variable as i understand it), so the value of y stays at 1.
>
> But in the second case, the variable y is retained by the "magic" of
> "in" command and thus can be iterated from 1 to 3, although it is the
> same function.
>
> If it possible to explain it simply (i'm not very skilled in lua so
> far) could you please explain me what happens really when using the
> "in" magic. Is this a way to make the local variable (like y here) of
> a function provisionally global, so that it can retains its value
> during the different calls to it, and when the "in loop" is finished
> it is taken back local again ?

Simplest explanation is this.  In the (1) case, you are creating a new
iterator each time though the loop, in which its y starts at zero.  In
the (2) case, it creates the iterator function once, and then uses each
time through the loop.  (The function named 'iterator' gets called once,
the function 'iterator' returns is called once per loop.)  To make the
(1) case similar, it should be written like this:

x = iterator(table)
for i = 1, 3 do
   x()
end

-- 
Michael Welsh Duggan
(mwd@cert.org)