Manual:DIL Manual/while()

From DikuMUD Wiki
< Manual:DIL Manual
Revision as of 23:22, 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

while

Instruction. Repeats a statement as long as a condition is true.

while (condition)
   statement

Tests condition, and while it is true runs the statement, usually a block in { }, and tests again. break leaves the loop at once; continue goes back to the test.

Notes

  • The condition is true when it is a non-zero integer, a unit or string that isn't null, or a list that isn't empty. A condition that fails (a field of a null unit) is false, so while (u.level > 5) stops when u becomes null.
  • Don't test a text field or a string list entry on its own, as in while (sl.[i]) or while (u.title): for these the test is the wrong way round, true when the text is empty. Write while (sl.[i] != "").
  • and and or evaluate both sides: (u != null) and (u.type == UNIT_ST_PC) still reads u.type. That is harmless here, since a failed field is false.
  • There is no do ... while and no for.
  • A loop that runs about 52000 instructions without a wait or pause gets the program stopped ("had endless loop" in the zone log). A long walk over the world's units needs a pause now and then.
  • A loop over a room's units that moves or destroys them should be a foreach(): after link(u, ...), u.next is in the other place.

Example

dilbegin unitptr first_weapon(ch : unitptr);
var
   u : unitptr;
code
{
   u := ch.inside;
   while (u != null)
   {
      if (u.type == UNIT_ST_OBJ)
         if (u.objecttype == ITEM_WEAPON)
            break;
      u := u.next;
   }
   return(u);                 // null when there is none
}
dilend

Finds the first weapon a character carries, or null.

See also