Basic Loops

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.

For Loops (Numeric)

The standard for loop iterates over a numeric range. It is highly efficient and common for fixed-count iterations.

To and Downto

  • Use to for an increasing range.
  • Use 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);
Result
Increasing:
1
2
3
Decreasing:
3
2
1

Step Keyword

The step keyword allows you to specify the increment or decrement value.

for var i := 1 to 5 step 2 do
  PrintLn(i);
Result
1
3
5

While Loops

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;
Result
Count: 1
Count: 2
Count: 3

Repeat..Until Loops

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
Result
Value: 5

Loop Control

You can modify the execution flow within any loop using jump statements:

  • break: Terminate the loop immediately.
  • continue: Skip to the next iteration.

For iterating over collections like arrays, sets, or strings, use the more modern for..in iteration.

On this page