Reputation: 47
im trying to understand the iterators, in many examples I founf something like this:
function square(iteratorMaxCount,currentNumber)
if currentNumber<iteratorMaxCount
then
currentNumber = currentNumber+1
return currentNumber, currentNumber*currentNumber
end
end
function squares(iteratorMaxCount)
return square,iteratorMaxCount,0 // why not return square(iteratorMAxCount,0)????
end
for i,n in squares(3)
do
print(i,n)
end
First I dont understand the line I comment, and I dont find an easy example of how to do a Stateful Iterator and a Stateless iterator. Can anybody help me? thanks
Upvotes: 0
Views: 238
Reputation: 28968
From Lua Reference Manual 3.3.5:
A for statement like
for var_1, ···, var_n in explist do block end is equivalent to the code: do local f, s, var = explist while true do local var_1, ···, var_n = f(s, var) if var_1 == nil then break end var = var_1 block end end Note the following:
explist
is evaluated only once. Its results are an iterator function, a state, and an initial value for the first iterator variable. f, s, and var are invisible variables. The names are here for explanatory purposes only. You can use break to exit a for loop. The loop variables var_i are local to the loop; you cannot use their values after the for ends. If you need these values, then assign them to other variables before breaking or exiting the loop.
So squares() has to return a function (square) a state (iteratorMaxCount) and an initial value (0) in order to work with a generic for loop.
Read the reference manual, Programming in Lua.
Upvotes: 2