FOREACH loop

The FOREACH loop provides a way to execute a block of statements for each element in an instance of an array:

  FOREACH type element IN array
    { statements; }
  END;

The type must be the type of the elements held in the array. The element is the variable that will become a reference to the current element in the array to be used by the block of statements. The array is the array to loop through.

The block of statements is executed starting with the first element in the array (index 0), repeating the block of statements for every element of the array. Execution will leave the FOREACH loop after the final element.

At the start of the FOREACH loop, the size of the array is stored. At the start of every loop, the array size is checked and if it has changed a runtime error will occur.

The array may be single-dimensional or a jagged array of any depth.

The array can refer to any available from the current scope upwards, or a new array using the curly brackets array initialisation syntax.

The element is a reference to the element in the array. Any change made to element is also reflected in the element in the array.

The FOREACH loop can be terminated early by using the BREAK statement. This causes execution to move to the statement after the END of the current loop.

Single-dimensional array examples

  INT[] array := {0, 1, 1, 2, 3, 5};

  FOREACH INT i IN array
    PRINT(i, "\n");
  END;
  FOREACH INT i IN {0, 1, 1, 2, 3, 5}
    PRINT(i, "\n");
  END;
  STRING[] array := {"0", "1", "1", "2", "3", "5"};

  FOREACH STRING s IN array
    PRINT(s, ", ");
  END;

Output

0, 1, 1, 2, 3, 5, 

Jagged array example

  INT[][] array2D := {{0, 1, 1, 2, 3, 5}, {2, 3, 5, 7}};

  FOREACH INT[] array IN array2D
    FOREACH INT i IN array
      PRINT(i, ", ");
    END;
    PRINT("\n");
  END;

Output

0, 1, 1, 2, 3, 5, 
2, 3, 5, 7, 

Unlike with other variables, the element in a FOREACH loop does not need to be defined at the start of the function. It only needs to be defined by the FOREACH statement itself. The element is only valid for the block of statements within the FOREACH loop. After the END of the FOREACH loop the element is no longer in scope and cannot be used again. Other FOREACH loops outside of the scope and in the same function may reuse the same element name.