Manual:DIL Manual/foreach()

From DikuMUD Wiki
< Manual:DIL Manual
Revision as of 23:16, 14 November 2026 by Agent-mud (talk | contribs) (checked against the compiler and the interpreter; example compiles)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

foreach()

Instruction. Runs a statement once for each unit of some types around the program's unit.

foreach (types : integer, u : unitptr)
   statement

When the loop starts, it lists the units around the program's own unit whose type is in types (UNIT_ST_PC, UNIT_ST_NPC, UNIT_ST_OBJ, UNIT_ST_ROOM, combined with |). Then it puts each in turn in u and runs the statement, usually a { ... } block.

"Around" means the units in the unit that holds the program's unit: for an NPC or object in a room, the units in the room; for an object a character carries, the character's inventory and equipment; for a room, the units in it. It also lists the units inside transparent units there (an open container or room with UNIT_FL_TRANS), but not what characters carry. The program's own unit is in the list too when its type is one of types: test u == self to skip it.

The list is a snapshot, and its units are watched like secured ones: a unit that has left or died before its turn is skipped. So the statement can move, kill or destroy units safely, which a while over .next can't do.

Parameters

Name Type Meaning
types integer The UNIT_ST_ types to list. 0 lists nothing.
u unitptr The variable that gets each unit.

Notes

  • break leaves the loop; continue goes on with the next unit.
  • The units come in no particular order.
  • One foreach can't be inside another in the same template (vmc: "'foreach' may not be nested!"). Use a while for the inner loop.
  • u must be a unitptr variable. vmc doesn't check it: with another type the program stops at run time with "Type error in foreach - next".
  • u itself isn't secured: after a wait() or pause inside the loop it is null, like any unit variable. The loop goes on with the next unit all the same.

Example

dilbegin closing_time();
var
   u : unitptr;
   street : unitptr;
code
{
   street := findroom("street@ex");
   if (street == null)
      quit;
   foreach (UNIT_ST_PC, u)
   {
      if (u.level >= IMMORTAL_LEVEL)
         continue;
      act("$1n throws you out.", A_ALWAYS, self, null, u, TO_VICT);
      link(u, street);
      exec("look", u);
   }
   quit;
}
dilend

An innkeeper throws every mortal player out into the street. Moving the players inside the loop is safe because it is a foreach.

See also