While Statement

While Statement

Flash CS4 ActionScript 3.0 Tutorial


How to Perform a Boolean Comparison Using a Loop with Flash ActionScript



Loops are handy pieces of code if you want to fill an Array, add several Loaders or check several pieces of data. In other words, loops work great to populate an array, movie clip or the stage. Once a loop starts, it consumes the processor resources. It is important that you don't create an endless loop that you can't escape.

Loops come in multiple varieties. Common loops include For, Do While and While statements. Note While statements can be used by themselves or in conjunction with Do statements

In this example we will demo a While statement that loads several shapes to the stage. For more information on other types of loops, see topics, Do While Statement, For Statement and Removing an External File with While Statement.


Step One

Open a new Flash document and name the default layer Actions.

Step Two

Open the ActionScript panel for the only keyframe in the Actions layer by Option double-clicking (PC - Alt double-clicking) the keyframe.

Step Three

Copy/Paste the following code in the ActionScript Panel:

var boxCount:int=1;


var cube01:Shape=new Shape;






cube01.x= boxCount*80;



Step Four

Click the Auto Format button to format the code.

Step Five

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Five rounded rectangles appear on the stage.

Dissecting the Code

The first line of the code at Step Three establishes a new variable named boxCount and sets it's value to one.

The while statement checks to make sure that the boxCount variable is less than six. If the while statement is true, all of the items inside the curly brackets occur.

A new Shape variable is introduced named cube01. Lines four through seven define the rounded rectangle shape.

The addChild() statement adds the object to the stage and the next line distributes the multiple objects across the stage.

The last line inside the curly brackets increments the boxCount variable by one for each pass through the statement.


Stock Images