Foreach statement (TADS 3)

From IFWiki

The foreach statement in TADS 3 allows you to easily loop over a collection, much like a for loop but it saves the author from defining index variables just to refer to each element in the collection.

Syntax

In TADS 3 only:

foreach (var in expression) { body }

Example

Suppose we want to print a list of numbers, one per line.

local lst = [2, 3, 5, 7, 11];

foreach ( local x in lst ) {
    "<<x>>\n";
}

Another example

This time, we want to add the names of every object in a room StartRoom to a list lst. Here's a way to do it using foreach.

local lst = [];

foreach ( local obj in StartRoom.contents ) {
    lst += obj.name;
}

Coding note

Note that because of the way the iteration is done, if you change the collection you are iterating over whilst the iteration is underway, the elements you iterate over are not affected. For example,

local lst = [1];

foreach ( local x in lst) {
    lst.append(x);
}

does not send the program into an infinite loop (which you would expect if foreach updated lst after each iteration). At the end of this code, lst is [1, 1]. See the TADS 3 documentation for more information.