The for statement has two forms: one numeric and one generic.
The numeric for loop repeats a block of code while a control variable runs through an arithmetic progression. It has the following syntax:
stat ::= for Name `=´ exp `,´ exp [`,´ exp] do block end
The block is repeated for name starting at the value of the first exp, until it passes the second exp by steps of the third exp. More precisely, a for statement like
for v = e1, e2, e3 do block end
is equivalent to the code:
do local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3) if not (var and limit and step) then error() end while (step > 0 and var <= limit) or (step <= 0 and var >= limit) do local v = var block var = var + step end end
Note the following:
var
limit
step
v
The generic for statement works over functions, called iterators. On each iteration, the iterator function is called to produce a new value, stopping when this new value is nil. The generic for loop has the following syntax:
stat ::= for namelist in explist do block end namelist ::= Name {`,´ Name}
A for statement like
for var_1, ···, var_n in explist do block end
do local f, s, var = explist while true do local var_1, ···, var_n = f(s, var) var = var_1 if var == nil then break end block end end
explist
f
s
var_i