Conditionals and Loops

Using conditions and loops, you can teach your Flash animations how to make decisions, and viewers will think both you and your animations are very smart. ActionScript provides a few different decision-making statements that you can use depending on your needs. In human-ese, they work like this:

  • If (this condition exists) do (these actions)

  • While (this condition exists) do (these actions)

  • For (X number of times) do (these actions)

Those three forms of decision-making may seem very similar, but as you'll see in the following explanations and examples, there are some important basic differences. You'll hear programmers refer to these decision-making statements using different terms, like program flow controls, conditionals, and loops. These tools have one thing in common: They all help you dictate whether or not ActionScript runs some specific lines of code.

Conditionals: if() and switch() Statements

Two of ActionScript's statements tackle the "If (this condition exists) do (these actions)" situations. The first and simplest state is appropriately called an if statement.

if() statements test a condition

The most basic if statements are built like this:

if (this is true) {do this}

So, if you're writing an ActionScript statement for a parking meter cop, it might look like this:

if (parkingMeterExpired==true) {writeTicket();}

It works like this: If the condition within the parentheses is true, then your code performs the statements within the curly brackets. If the expression ...

Get Flash CS5: The Missing Manual now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.