Loops in ActionScript

written by: Milan Midovich; article published: year 2007, month 07;



In: Categories » Computers and technology » Flash » Loops in ActionScript

The syntax for creating loops in ActionScript is a little more complex than the simple if statement. Fortunately, it is almost identical to how loops are created in languages such as C, C++, and Java.

The for Loop

The primary type of loop is the for loop. It looks like this:

for(var i=0;i<10;i++) {     
 trace(i);  }  

If you run this code in a frame script, you get the numbers 0 through 9 placed in the Output window. The loop counts from 0 to 9, changing the local variable i along the way.

As you can see, a for statement has three parts. Each part is separated by a semicolon.

The first part is a variable declaration. In this case, the local variable i is created and set to 0. This first part of the for statement is executed once, before the loop starts.

The second part of the for statement is a condition. In this case, it tests to see whether i is less than 10. The for loop continues to run as long as this condition is true. When the loop starts, i is equal to 0, which is certainly less than 10, so the loop begins.

The third part of the for statement is an operation to be performed every time the loop loops. In this case, i is incremented by 1. This operation is performed after each iteration of the loop because the ++ operator is placed after the i. If it were placed before the i, such as ++i, the operation would take place before the commands inside the loop are executed.

Inside the brackets are the commands to be executed each time through the loop. Let's play computer and see how the example works:

  1. The local variable i is created and set to 0.

  2. A check is made to make sure that i is less than 10. Because it is, the loop is allowed to continue.

  3. A note is made that the variable i should be incremented by 1 when each iteration of the loop is complete. For now, i remains at 0.

  4. The trace command then sends the contents of i to the Output window, in this case 0.

  5. The iteration of the loop ends, and i is increased by 1.

  6. The loop starts again, and the check is made to see whether i is less than 10. It is, because i is now 1, and the loop is allowed to continue.

  7. The trace command sends the contents of i to the Output window, in this case 1.

This continues, with i increasing by 1 each time, until the 10th time through the loop. Then the following happens:

  1. The iteration of the loop ends, and i is increased by 1. Its value is now 10.

  2. The loop starts again, and the check is made to see whether i is less than 10. It is not because i is equal to 10. The loop ends.

  3. The next line after the closing bracket at the end of the loop executes, and the loop is over.

Other Kinds of Loops

The for loop is the most common kind of loop. However, two other kinds of loops are the while loop and the do loop.

The while loop looks like this:

while (a != 7) {      
// more code here  }  

As you can see, this is a much simpler loop than a for loop. It actually looks just like an if statement, except that the code in the brackets will continue to run over and over again until the condition is met. This being the case, it is easy to create undesirable infinite loops. You would have to make sure that the code inside the loop alters a in some way so that it eventually achieves the value of 7 and the loop ends.

The sibling to the while loop is the do loop. Here is what it looks like:

do {     
// more code here  
}  while (a != 7);  

The while and do loops are actually the same thing, except that the condition is checked in different places. In the while loop, the condition is checked before each iteration of the loop, whereas in the do loop, it is checked after each iteration of the loop. The difference is that the do loop always runs at least once.

Breaking Out of Loops

All three kinds of loops can use two optional commands to change the flow of the loop. The first command, break, stops the loop and jumps right to the instruction following the loop.

The other command, continue, terminates the current pass through the loop but starts the next pass through the loop right away.

For instance, if instructions A, B, and C are inside the loop, and instruction B performs a continue command if a certain condition is met, instruction C will be skipped, and the loop will start again at A. If it was a break command instead, C would be skipped and the loop would end.

legal disclaimer

1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service

Useful tools and features

Translate this article to...    Send this article to you or to a friend

Link to this article from your page   
If you like this article (tutorial), please link to it from your web page using the information above. Linking to this page, this is the only way to help us improve our service, the same time providing your visitors with a way to improve their online experience.

related articles

1. ActionScript: Filling a Shape with a Solid or Translucent Color
Use the beginFill( ) and endFill( ) methods to initiate and close a shape drawn at runtime. To draw a filled shape, call beginFill( ) prior to any other drawing methods, including the custom methods you have defined such as drawCircle( ) and drawPolygon( ). Invoke endFill( ) after calling other drawing methods to create the shape. You cannot apply a fill to an existing shape drawn at authoring time or runtime. You must invoke beginFill( ) before drawing the shape to be filled. This example creates a solid blue ...

2. Drawing a rectangle using ActionScript
Create a custom MovieClip.drawSimpleRectangle( ) method using the Drawing API and invoke it on a movie clip. To draw a simple rectangle, specify the stroke's attributes using the lineStyle( ) method and then draw four lines using the lineTo( ) method: // Create rectangle_mc with a depth of 1 on the main timeline. _root.createEmptyMovieClip("rectangle_mc", 1); // Specify a one-pixel, solid, black line. rectangle_mc.lineStyle(1, 0x000000, 100); // Draw four lines to form the perimeter ...

3. How to draw a rectangle with rounded corners
You want to draw a rectangle with rounded corners, an offset, or rotation.Create a custom MovieClip.drawRectangle( ) method using the Drawing API and invoke it on a movie clip. The drawSimpleRectangle( ) method is, as the name suggests, quite simple. Let's create a more complex version that also: Draws a rectangle with a specified angle of rotation Let's you specify the rectangle center's coordinates Can draw a rectangle with rounded corners The drawRectangle( ) method accepts...

4. Reusing and Organizing Code in Flash Movies
You want to reuse code that you've created for one project in another Flash movie. Or you want to write your ActionScript code in an external text editor. Place your ActionScript code in external .as files and use the #include directive to add them to your Flash movies: // Adds all the code within MyActionScriptFile.as to your Flash movie. #include "MyActionScriptFile.as" Use the #include directive to incorporate code from external text files into your Flash movie during compilation from a .fla file ...

5. Drawing a Circle using ActionScript
Create a custom MovieClip.drawCircle( ) method using the Drawing API and invoke it on a movie clip. You can create a circle in ActionScript with eight curves. Fewer curves results in a distorted circle and too many curves hinders performance. Let's create a custom method of the MovieClip class for drawing circles. This method, drawCircle( ), allows for three parameters: radius The radius of the circle x The x coordinate of the circle's center point. If undefined, the circle is centered at x =...

6. ActionScript: Repeating a Task at Timed Intervals
You want to perform an action or actions at a specific timed interval. Use the setInterval( ) function. The setInterval( ) function allows you to specify an interval (in milliseconds) at which your Flash movie will invoke a function. Use setInterval( ) to perform a particular action over time but not necessarily at the frequency of the frame rate of the movie. // Define a function. function myIntervalFunction ( ) { // Output the difference between the current timer value and its value from the ...

7. Mouse Location Flash Script
Not only can you get the location of a movie clip on the screen, you can even get the location of the mouse, also known as the cursor. What is the difference between the mouse and the cursor? The mouse is the physical device attached to your computer. You may even have a track pad or tablet instead. The cursor is the graphic that moves around the screen as you move your mouse. So, technically, cursor is the term I should be using here. However, ActionScript uses the term mouse in its keywords. I will therefore use mouse and cursor i...

8. ActionScript: Performing Actions Conditionally
You want to perform an action only when a condition is true. Use an if statement or a switch statement. You often need your ActionScript code to make decisions, such as whether to execute a particular action or group of actions. To execute an action under certain circumstances, use one of ActionScript's conditional statements: if, switch, or the ternary conditional operator (? :). The conditional statements allow you to make logical decisions, and you'll learn from experience which is more appropriate for a given situ...

9. Enhancing Standalone Projector
You want to create an enhanced Standalone Projector with features such as borderless playback, custom titles, no Flash menus, and so on. Use a third-party tool such as SWF Studio or SWFKit to create the Projector from your completed Flash movie. SWF Studio is a third-party utility that helps you overcome some of the limitations of regular standalone Flash Projectors. However, SWF Studio produces Windows projectors only. Also note that the resultant projector files are rather hefty (minimum file size is around 1.5 MB). The...