Loops
While loops
In a while loop, you execute a certain block of code while a condition is true. The syntax is as follows:
The example below counts from 1 to 10:
The following example prints nothing. The while loop is skipped because the condition is initially false:
Do-while loops
Do-while loops are similar to while loops, except that the block of code is executed at least once, unconditionally. It is repeated while a condition is true. Syntax:
The example below counts from 1 to 10:
The following example prints the number 20. Since the condition is false, the block of code is executed only once:
Note: do-while loops are available since SurgeScript 0.6.0.
For loops
A for loop is a more controlled repetition structure compared to a while loop. For loops support an initialization command, a condition and an increment command. The syntax is as follows:
The for loop above is equivalent to:
The example below counts from 1 to 10:
Foreach
Foreach loops are used to iterate throughout iterable collections (such as Arrays and Dictionaries). Basically: for each element x
in the iterable collection, do something with x
. The syntax is as follows:
The example below counts from 1 to 10:
The example below iterates over a Dictionary:
dictionary = { "a": 1, "b": 2, "c": 3 };
foreach(entry in dictionary) {
Console.print(entry.key);
Console.print(entry.value);
}
Implementing your own iterable collections
The foreach loop can be used with any iterable collections, not only Arrays and Dictionaries. You may even implement your own!