Do-While Loop
Do-while-loops are loops with a similar behaviour to while-loops, with the main difference being that do-while loops run the statement once before starting evaluating its condition. Afterwards the statement is only run if the specified condition is met.
Syntax
do STATEMENT while (CONDITION);
Execution Schema
- Run
STATEMENT
(Only the first time). -
Check
CONDITION
, if it exists, before running theSTATEMENT
again. IfCONDITION
isfalse
, then the loop will be stopped! - Run
STATEMENT
ifCONDITION
wastrue
.
Examples
// ✓ Simple loop
var var1: num = 0;
do {
var1++; // This statement is evaluated once at the start even if the condition isn't met
} while (var1 >= 3);
call print(f"'var1' is now '{var1}'"); // -> 'var1' is now '1'
// ✓ Simple loop, where initially the condition isn't met but after the first run it becomes true
var var2: num = 0;
do {
var2++;
} while (var2 > 0 && var2 <= 25)
call print(f"'var1' is now '{var2}'"); // -> 'var1' is now '26'
// X Infinite Loop - Avoid this, as it results in your program freezing/running forever
do {
call print("An unnecessary print!");
} while (true)