While loop

From ZCWiki
Revision as of 03:25, 8 June 2009 by Joe123 (talk | contribs) (The Deliberately Infinite Loop)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Use the while loop when you want certain things to happen repeatedly only when a particular condition is true.

Syntax and Execution

The while loop has the following syntax:

while(test-expression){ 
  // statements inside the curly braces
  // are only executed if test-expression
  // is true.
}

where test-expression is an expression whose "thruthness" or "falsness" can be determined. If test-expression evaluates to true, then the statements inside the braces are executed and test-expression is checked again. Execution will loop in this fashion until test-expression evaluates to false, in which case the while loop is exited and the statements after the loop's closing brace are executed.

Note that because of this behavior, something inside the braces must be capable of changing the value of test-expression to false such that the loop may eventually be exited (though see Tips and Tricks), otherwise the loop may repeat forever, possibly freezing Zelda Classic gameplay.

Also note that since test-expression is checked at the beginning of the loop, it is possible that the statements in the braces will never be executed (that is, if test-expression evaluates to false the first time the while loop is encountered, nothing in the loop will be executed).

Examples of some expressions include:

  • Link->HP >= 32
True as long as Link has more than 32 hitpoints.
  • X != 10
True as long as variable X isn't 10.
  • Y == 10
True as long as variable Y is equal to 10.

Expressions can be as simple or complex as needed, as long as they evaluate to true or false. Note that you do not end the expression with a semicolon.

Tips and Tricks

The Deliberately Infinite Loop

It was noted earlier that if the statements inside the while loop don't change the test-expression being evaluated by the loop, you run the risk of getting stuck in an infinite loop. However, there are cases where you actually need to do this. By default scripts only run once - and only during a single frame of gameplay - when they are called by the Zelda Classic engine. This means that if, for example, you have a FFC script that needs to monitor something the entire time Link is on a particular screen, you need to put it in an infinite loop. If you do this you must also include calls to the Waitframe() or Waitframes() function so Zelda Classic has a chance to process other events - otherwise you will lock up the game.

Note that this technique does not work for item scripts.

A deliberately infinite loop will be constructed like this:

while(true){ 
  // statements inside the curly braces
  // are executed continually,
  // unless 'Quit();' or 'break;' is called
  Waitframe(); // Waitframe is called to stop the loop from crashing the system
}

See Also