lua-users home
lua-l archive

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


Aaron Brown wrote:
PA wrote:


At first glance there are 4 different ways to write a
"for" loop ( "=", "in", "in ipairs()", "in pairs()" ).

Let make that 5. There is a "in next()" as well. Sigh...

that is not correct : for ... in pairs(), in ipairs(), in next() are the same thing as far as the language goes - each of pairs, ipairs, etc is a function that returns an iterator function. also io.lines()


there are only 2 "for" constructs -
1/ the numeric for (PIL ch 4.3)

for var=exp1,exp2,exp3 do
  something
end

will iterate for each value of var from exp1 to exp2 in steps of exp3

for i = 10,1,-1 do print(i) end
will loop from 10 to 1, decrementing.

(exp3 defaults to 1, which is reasonable, although one might expect it to be nil)

2/ the generic for (PIL ch 7.2)

for <var-list> in <exp-list> do
  something
end

most often used as
for var1, var2 in iterator_func do
  something
end

where iterator_func is lines(), pairs(), ipairs() etc. this will loop until iterator_func returns nil.

note that pairs()/ipairs() is evaluated ONCE - it returns a function that is called each loop

Adrian