foreach() loops can be used to iterate over the elements of an array or mapping . The array form is:
foreach ( in) { ... }
Where
is exactly the same as doing:
Note that
The second form is used to iterate over a mapping :
Each time through the loop, the first var is set to a key from the mapping ,
and the second is set to the corresponding value, so:
is the same as the considerably more complex:
See also the summary of loops .
Beek @ZorkMUD, Lima Bean, IdeaExchange, TMI-2, and elsewhere
int x;
foreach (x in ({ 1, 2, 3, 4 })) {
printf("%i ", x);
}
int x, i, n;
int *y = ({ 1, 2, 3, 4 })
n = sizeof(y);
for (i = 0; i < n; i++) {
x = y[i];
printf("%i ", x);
}
foreach (, in
int x, y;
foreach (x, y in ([ 1 : 2, 3 : 4, 5 : 6 ]) ) {
printf("%i : %i\n", x, y);
}
int x, y;
mapping m = ([ 1 : 2, 3 : 4, 5 : 6 ]);
int *k = keys(m);
int n = sizeof(k);
for (int i = 0; i < n; i++) {
x = k[i];
y = m[x];
printf("%i : %i\n", x, y);
}
Tim Hollebeek