Manual:DIL Manual/foreach()
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
foreachcan't be inside another in the same template (vmc: "'foreach' may not be nested!"). Use awhilefor the inner loop. umust be aunitptrvariable. vmc doesn't check it: with another type the program stops at run time with "Type error in foreach - next".uitself isn't secured: after await()orpauseinside 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.