While loop

From ZCWiki
Revision as of 01:34, 15 January 2008 by ScaryBinary (talk | contribs) (First attempt at describing the while loop.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

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

Syntax and Execution

The while loop has the following syntax:

  // statements inside the curly braces
  // are only executed if expression
  // is true.

where expression is an expression whose "thruthness" or "falsness" can be determined. If expression evaluates to true, then the statements inside the braces are executed and expression is checked again. Execution will loop in this fashion until 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 expression 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 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 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 if 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 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. Scripts only run once 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 change to process other events - otherwise you could lock up the game.

See Also