The 'for' Loop
The
for
loop is a very 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:
for([Initialisierung]; [Bedingung]; [Inkrementierung]))
[Auszuführende Anweisung];
- 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 manually interrupted (i.e. using the break
keyword). This is an infinite loop:
for(;;)
Log("Fl00d!");
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:
var i = 0;
while(++i <= 10)
Log("%d", i);
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 a
to the log.
Using for to iterate over a map
Another function of the for
-loop is iterating over key-value-pairs of maps. The script looks like this:
for(var key, value in m)
Log("%v => %v", key, value);
This script would output all entries of the map m
to the log in the format "Key => Value".
Further examples:
for(var i = 10; i >= 1; i--)
Log("%d", i);
Counts backwards from 10 to 1.
Var(0) = 2;
Var(1) = 1;
Var(2) = 4;
Var(3) = 3;
Var(4) = 2;
for(var i = 0; Var(i) != 3; i++)
Log("Var(%d) = %d", i, Var(i));
Prints the indexe local variables (see
Var()
), until the value '3' is encountered. The result would be:
Var(0) = 2
Var(1) = 1
Var(2) = 4
Peter, Juni 2004