Man foreach

From LSWiki

(Difference between revisions)
Jump to: navigation, search

Current revision

Contents

Synopsis

  • foreach ( : <expr>) <statement>;
  • foreach (<var>, <var2>, ... ,<varN> : <expr>) <statement>;

/* MudOS compatibility only - not for new code: */

       foreach (<var> in <expr>) <statement>;
       foreach (<var>, <var2>, ... ,<varN> in <expr>) <statement>;

Description

<expr> is evaluated and has to yield an array, a string or a mapping. The values of <expr> (in case of the string, the integer values of the characters) are then assigned one after another to <var> and <statement> is execute for every assignment.

If <expr> is a mapping, the keys are assigned to <var>, and the values for each key are assigned in order to <var2>..<varN>. If there are more values than variable, the extraneous values are ignored.

If there are more variables than necessary, the unneeded ones are not changed.

Every <var> specification can declare a new local variable, whose scope is the whole foreach() statement.

A 'break' in the 'statement' will terminate the loop. A 'continue' will continue the execution from the beginning of the loop.


WHAT HAPPENS IF <expr> IS CHANGED IN THE LOOP?

If <expr> yields an array:

        * assignments to single array elements or to array ranges effect
          the values assigned to the variable:
            a = ({1, 2, 3})
            foreach(x : a) { a[1..2] = ({4, 5}); write(x+" "); }
          will write ("1 4 5 ").
        * operations which implicitely copy the array (this includes
          range assignments which change the size) don't have an effect
          on the loop.

If <expr> yields an mapping, the loop will run over the indices the mapping had at the begin of the loop. Deleted indices are silently skipped, new indices ignored, but changes of the data of existing indices are acknowledged.

If <expr> yields a string, it can't be changed anyway.


Warning

The additional syntax forms using "in" as keyword are meant to make re-engineering of MudOS objects easier. Do not use them for newly written code, as they may not be available in future.


Examples

   // Call quit() in all interactive users
       foreach(o : users()) o->quit();
       foreach(object o : users()) o->quit();
   // Print the contents of a mapping <m>
       foreach(key, value : m) printf("%O:%O\n", key, value);
       foreach(mixed key, mixed value : m) printf("%O:%O\n", key, value);

See Also

for(LPC)

Personal tools