Using operators to manipulate values

Operators are commonly used to manipulate values in Flash. For example, you might want to create a game in Flash where the score changes depending on the user's interaction with instances on the Stage. You can use a variable to hold the value and operators to manipulate the value of the variable.

For example, you might want to increase the value of a variable called myScore. The following example demonstrates how to use the + (addition) and += (addition assignment) operators to add and increment values in your code.

To manipulate values using operators:

  1. Create a new Flash document.
  2. Open the Actions panel (Window > Actions) and type the following code into the Script pane:
    // example one
    var myScore:Number = 0;
    myScore = myScore + 1;
    trace("Example one: " + myScore); // 1
    
    // example two
    var secondScore:Number = 1;
    secondScore += 3;
    trace("Example two: " + secondScore); // 4
    
  3. Select Control > Test Movie.

    The Output panel displays the following text:

    Example one: 1
    Example two: 4
    

    The addition operator is fairly straightforward, because it adds two values together. In the first code example, it adds the current value of myScore and the number 1, and then stores the result into the variable myScore.

The second code example uses the addition assignment operator to add and assign a new value in a single step. You can rewrite the line myScore = myScore + 1 (from the previous exercise) as myScore++ or even myScore += 1. The increment operator (++) is a simplified way of saying myScore = myScore + 1, because it handles an increment and assignment simultaneously. You can see an example of the increment operator in the following ActionScript:

var myNum:Number = 0;
myNum++;
trace(myNum); // 1
myNum++;
trace(myNum); // 2

Notice that the previous code snippet doesn't have assignment operators. It relies on the increment operator instead.

You can manipulate the value of a variable using operators while a condition is true. For example, you can use the increment operator (++) to increment the variable i while the condition is true. In the following code, the condition is true while i is less than the value of 10. While that is true, you increment i one number higher using i++.

var i:Number;
for (i = 1; i < 10; i++) {
    trace(i);
}

The Output panel displays the numbers 1 through 9, which is i incrementing in value until it reaches the end condition (i is equal to 10), when it stops. The last value displayed is 9. Therefore, the value of i is 1 when the SWF file starts playing, and 9 after the trace completes.

For more information on conditions and loops, see About statements.