Loops allow you to execute a block of code multiple times. DWScript provides three fundamental loop constructs: for for counted ranges, while for entry-controlled conditions, and repeat..until for exit-controlled conditions.
The standard for loop iterates over a numeric range. It is highly efficient and common for fixed-count iterations.
to for an increasing range.downto for a decreasing range.The loop variable can be declared inline using the var keyword, which scopes it strictly to the loop body.
PrintLn('Increasing:');
for var i := 1 to 3 do
PrintLn(i);
PrintLn('Decreasing:');
for var j := 3 downto 1 do
PrintLn(j); Increasing: 1 2 3 Decreasing: 3 2 1
The step keyword allows you to specify the increment or decrement value.
for var i := 1 to 5 step 2 do
PrintLn(i); 1 3 5
The while loop is entry-controlled: the condition is checked before the first iteration. If the condition is false initially, the loop body never executes.
var count := 1;
while count <= 3 do begin
PrintLn('Count: ' + count.ToString);
count := count + 1;
end; Count: 1 Count: 2 Count: 3
The repeat loop is exit-controlled: the condition is checked after each iteration. This guarantees that the loop body will execute at least once.
Note that unlike while, repeat continues until the condition becomes true. Also, the begin..end block is not required between repeat and until.
var i := 5;
repeat
PrintLn('Value: ' + i.ToString);
i := i + 1;
until i > 3; // Condition is true immediately, but loop ran once Value: 5
You can modify the execution flow within any loop using jump statements:
For iterating over collections like arrays, sets, or strings, use the more modern for..in iteration.