FOREACH

Statement

Syntax

Walks a list or a map from its first element to its last. Inside the loop, the element of this pass is the current one.

FOREACH <collection>()
  <statements>
NEXT [<collection>()]

Parts

<collection>A list declared with NewList, a map declared with NewMap, or a list or map field of a record (bag.items). The parentheses are required.
<statements>The body. <collection>() reads or changes the element of this pass; MapKey() gives a map entry's key.

Good to know

  • A map is walked in the order its entries were created.
  • Deleting the current element inside the loop is safe: the loop goes on with the next one. EXIT and CONTINUE work as in any loop.
  • FOREACH a and NEXT a without parentheses are compile errors; NEXT alone is fine. NEXT naming another collection is refused. There is no ENDFOREACH.
  • FOREACH does not work on arrays: use FOR i = 0 TO a.length.
  • FOREACH moves the collection's one cursor. A nested FOREACH over the same list, or a call that moves the cursor, changes where the outer loop is. After a full pass there is no current element: ListIndex() returns -1.

Example

NewList a.i()FOR k = 1 TO 5  AddElement(a())  a() = kNEXTFOREACH a()  IF Mod(a(), 2) = 0 THEN DeleteElement(a())NEXTFOREACH a()  Console(Str(a()))   ' 1, then 3, then 5NEXT a()NewMap stock.i()stock("apple") = 3stock("pear") = 5FOREACH stock()  Console(MapKey(stock()) + " = " + Str(stock()))   ' apple = 3, then pear = 5NEXT
In the manual : Arrays, lists and maps