This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.
|Programming in Lua|
|Part I. The Language Chapter 4. Statements|
The for statement has two variants: the numeric for and the generic for.
A numeric for has the following syntax:
for var=exp1,exp2,exp3 do something endThat loop will execute
somethingfor each value of
exp3as the step to increment
var. This third expression is optional; when absent, Lua assumes one as the step value. As typical examples of such loops, we have
for i=1,f(x) do print(i) end for i=10,1,-1 do print(i) end
The for loop has some subtleties that you should learn
in order to make good use of it.
First, all three expressions are evaluated once, before the loop starts.
For instance, in the first example,
f(x) is called only once.
Second, the control variable is a local variable automatically
declared by the for statement
and is visible only inside the loop.
A typical mistake is to assume that the variable still exists after
the loop ends:
for i=1,10 do print(i) end max = i -- probably wrong! `i' here is globalIf you need the value of the control variable after the loop (usually when you break the loop), you must save this value into another variable:
-- find a value in a list local found = nil for i=1,a.n do if a[i] == value then found = i -- save value of `i' break end end print(found)Third, you should never change the value of the control variable: The effect of such changes is unpredictable. If you want to break a for loop before its normal termination, use break.
|Copyright © 2003–2004 Roberto Ierusalimschy. All rights reserved.|