Loops
Repeat instructions safely with WHILE and FOR loops in MiniScript+.
On this page
Loops repeat a block of instructions. They are useful for processing a sequence, validating input, or running a calculation several times.
WHILE loops
A WHILE loop repeats while its condition remains true.
counter = 0WHILE counter < 3 PRINT counter counter = counter + 1ENDThe output is:
012The loop has three parts:
- initialize the state before the loop;
- check a condition before every iteration;
- update the state inside the loop.
FOR loops
Use FOR when the start, end, and step are known in advance.
FOR number = 1 TO 5 PRINT numberENDAdd STEP to change the increment:
FOR number = 10 TO 0 STEP -2 PRINT numberENDChoose the right loop
| Situation | Recommended loop |
|---|---|
| A known number of repetitions | FOR |
| Repeat until a condition changes | WHILE |
| Walk through a numeric interval | FOR |
| Validate repeated user input | WHILE |
Avoid infinite loops
An infinite loop never makes its condition false.
counter = 0WHILE counter < 5 PRINT counterENDThe update is missing
The example never changes
counter. Addcounter = counter + 1inside the loop before running it.
Nested loops
A loop may contain another loop. Use indentation to keep the structure readable.
FOR row = 1 TO 3 FOR column = 1 TO 3 PRINT row * column ENDENDNested loops can perform many operations, so check the expected number of iterations before using them with large ranges.