Manual:DIL Manual/while()
Jump to navigation
Jump to search
Contents
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 whenubecomes null. - Don't test a text field or a string list entry on its own, as in
while (sl.[i])orwhile (u.title): for these the test is the wrong way round, true when the text is empty. Writewhile (sl.[i] != ""). andandorevaluate both sides:(u != null) and (u.type == UNIT_ST_PC)still readsu.type. That is harmless here, since a failed field is false.- There is no
do ... whileand nofor. - A loop that runs about 52000 instructions without a
waitorpausegets the program stopped ("had endless loop" in the zone log). A long walk over the world's units needs apausenow and then. - A loop over a room's units that moves or destroys them should be a foreach(): after
link(u, ...),u.nextis 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.