There are two broad classes of the For statement in the Lua programming language:: value for loop generic for loop value for loop
The value for loop syntax format in the Lua programming language:
For Var=exp1,exp2,exp3
do < actuators > End
var changes from Exp1 to EXP2, each time it changes to exp3 increments of Var, and executes an "Executive Body". EXP3 is optional and, if not specified, defaults to 1. Instance
For I=10,1,-1 does
print (i)
end
For three expressions are evaluated once before the start of the loop, and are no longer evaluated. For example, the above f (x) is executed only once before the start of the loop, and the result is used in a subsequent loop.
function f (x)
print ("function", x) return x*2 end for
i=1,f (5) Does
print (i)
end
Output results:
function 5
1
2
3
4
5 6 7 8 9 10
You can see that the function f (x) executes only once before the loop starts. generic for Loop
A generic for loop traverses all values through an iterator function, similar to a foreach statement in Java.
Generic for-loop syntax format in LUA programming languages:
--Print all values of array a for
i,v in Ipairs (a) does
print (v) End
I is the array index value, and V is the array element value of the corresponding index. Ipairs is an iterator function provided by LUA to iterate over an algebraic group.
Instance
Loop array Days:
Days = {"Suanday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} for
i,v into Ipairs (days)
do Print (v) End