Next: , Previous: , Up: Expressions And Statements   [Index]


7.3 The For Statement

For selected collection types, data traversal is possible by the ‘for’ statement.

    for (i, a in l) {
	o_(i, ": ", a, "\n");
    }

In between the ‘for’ lead parantheses, one or two variable names separated by comma are followed by the literal ‘in’ and an expression. The expression evaluates to a collection data type fitted for ‘for’ traversal and the types of the variables match one of the traversal modes allowed by the collection.

The statement will see the braces block executed repeatedly and over the collection bound data. The traversal variables will be set for every iteration to a next set of values. The first variable is always the position and its type matches the collection position type. Thus, the variable is an ‘integer’ for ‘list’ and ‘index’ collections, ‘text’ or ‘data’ for ‘record’ collections. The second variable, if present, is set to the position associated data. Its type is one of those allowed by the traversed collection, with some collection types allowing any type.

See The List Library.

See The Index Library.

See The Record Library.

Iterating over the keys in a ‘record’ associative table is:

    record r;
    text s;

    # add data to -r-
    r_fit(r, "AAA", 0, "BB", 1, "C", 2);

    for (s in r) {
	# show -s-
	o_(s, "\n");
    }

The ‘for’ statement sees the position variable set to the first position in the collection for the first iteration, and to the next position afterwards, until there is no next position.

The position variable may be modified inside the loop, and the next visited position will be set from the modified value.

The ‘for’ statement is equivalent with the if-do-while syntax:

    if (set for initial position in data collection) {
	do {
	} while (set for the next position);
    }

The ‘for’ enabled data types will likely allow a proper if-do-while syntax for data traversal, by appropriate functions.

Iterating over the keys and real data in an ‘index’ associative table is:

    integer p;
    index x;
    real a;

    i_fit(x, 0, 1r, 1, .5, 2, .25, 3, .125);

    for (p, a in x) {
	o_(p, " ", a, "\n");
    }

Next: , Previous: , Up: Expressions And Statements   [Index]