forloop is a convenient loop with starting initialization. It is most often used as counting loop. It will take three statements as parameters, each separated by a ';' semicolon. Followed by the code block to be executed:
The 'for' Loop
for([Initialization]; [Condition]; [Incrementation])) [Statement to be executed];
- The first statement will be executed once at the beginning of the loop. This is a good place to initialize counter variables.
- The second statement contains the loop condition. As soon as this condition returns 'false', the loop execution is stopped. The condition is checked before each loop execution.
- The third statement is executed after each loop execution. This is a good place to count up or down your counter variables.
It is possible to omit any of the three statements. If there is no condition statement, then the loop will run forever unless it is interrupted from the loop body (i.e. using the
breakkeyword). This is an infinite loop:
Using for as a counting loop
This is the most common use of the for loop. If, for example, you want to print all numbers from 1 to 10, you would write:
for(var i = 1; i <= 10; ++i) Log("%d", i);
Notice: the following while loop would do exactly the same:
Using for to iterate over an array
Another function of the
for-loop is iterating over arrays. Each element of the array is stored in the variable and the loop body executed for that element. The script looks like this:
for(var element in a) Log("%v", element);
This script would output all elements of the array
ato the log.
for(var i = 10; i >= 1; i--) Log("%d", i);
Counts backwards from 10 to 1.