lua-users home
lua-l archive

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


Hi,

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 ?

Maybe this is done by assigning this local variable to a global one that is defined provisionally during the use of the "in loop" (and delete at the end of the loop), and when looping in fact you use this global variable instead of the local one ?

Also i found a particular syntax for iterator's use that i don't understand and I didn't find documentation on it :

-----------------------------------------------
function square(iteratorMaxCount,tot)
   local currentNumber=tot
      if currentNumber<iteratorMaxCount then
         currentNumber = currentNumber+1
         return currentNumber, currentNumber*currentNumber
      end
end

for i,n in square,3,0 do
  print(i,n)
end
----------------------------------------------

What means this particular way to call the function square: "square,3,0" ?
apparently this is not equivalent to "square(3,0)" as this syntax make an error.


Thank you very much for your help