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_
, and _step_
are invisible variables. The names are here for explanatory purposes only.
v
is local to the loop; you cannot use its value after the for ends or is broken. If you need this value, assign it to another variable before breaking or exiting the loop.
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* explist1 *do* block *end* namelist ::= Name {`*,*` Name}
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_) _var_ = _var_1_ if _var_ == nil then break end _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.
_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.