4. ActionScript and Math

ActionScript has tons of mathematical operators built in to the language to help you evaluate mathematical equations. Now, I wouldn’t throw away your handheld calculator just yet. ActionScript has a lot of power, but it’s designed to help with your applications, not for general use. In addition to these mathematical operators, there are some functions that can help with common mathematical tasks like rounding numbers.

In this section, you’ll learn all the basic arithmetic operators that you’ll use in ActionScript. Also, there are some convenient shortcuts to make working with math easier that you’ll cover as well.

Mathematical Operators

In ActionScript, you can use simple math operators to perform arithmetic functions with your numbers or variables. The math functions that are part of ActionScript are nearly identical to basic math functions that you already know. Some of the symbols and names are different, but the principles are the same.

Addition and Subtraction

Let’s get started with adding and subtracting numbers.

1. Create a new ActionScript 3.0 project in Flash Professional CS5.5 and enter the following code into the timeline:

// Math operators: addition and subtraction
trace ( 2 + 3 );
trace ( 3 - 2 );

2. Run the project and look at the Output panel; you’ll see the following:

5
1

This shouldn’t be surprising, since you are adding and subtracting the numbers. You use the + and operators to indicate that you are adding or subtracting. One thing to note is the white-space characters used in the example. Notice the spaces between the operators and the numbers. This is for readability and doesn’t affect the execution of the code. You can remove the spaces if you want, for example:

trace ( 2 + 3 );
trace (2+3);

These two lines perform exactly the same function and will generate the same result.

Addition or Concatenation?

In the previous chapter, you used the + sign, but it wasn’t a mathematical operator. You can use the + operator to do two things. When working with strings, the + operator is called the concatenation operator and takes two strings and combines them together, in essence gluing the end of one string to the beginning of the next. When working with numbers, the + operator is the addition mathematical operator, adding two numeric values together and generating a new numeric result.

Look at the following example.

1. Remove the existing code and enter the following code:

// Addition vs. Concatenation
trace ( 2 + 2 ); // addition
trace ( "two" + "two" ); // concatenation
trace ( "2" + "2" ); // concatenation

2. Run this code; you’ll see the following displayed in the Output panel:

4
twotwo
22

The first line of code in the example is pretty simple; you are adding the numbers 2 and 2 using the addition operator, resulting in a value of 4.

The second line of code has two strings, denoted by quotation marks, that are being “glued” together, creating a single string using the string concatenation operator. The result is “twotwo.”

The last line uses the number 2 on both sides of the operator. Notice that the numbers are surrounded by quotation marks, which means that it is no longer a number value, but instead the character 2. When you force the number 2 to be a string using quotation marks, the + operator concatenates the strings, “gluing” them together forming the string, 22.

What makes this confusing is that the Output panel doesn’t distinguish between strings and numbers. So, when you see 22 in the Output panel, is it a number or a string? There is a way to find out the type of a value and display it: by using the typeof statement.

3. To see how typeof works, update the previous example as follows:

// Addition vs. Concatenation
trace ( typeof(2 + 2) ); // addition
trace ( typeof("two" + "two") ); // concatenation
trace ( typeof("2" + "2") ); // concatenation

4. Run this updated example; you’ll see the following in the Output panel:

number
string
string

What is happening is that the operation (either addition or concatenation) is taking place, and the typeof statement is determining the type of the result and then sending that to the Output panel via the trace statement.

Now for one final twist. If you mix up the number and string types, what happens?

5. Replace the existing code with the following:

trace ( 2 + "2" );

Wow. Now you have a number on the left side, and a string on the right side. Who wins?

6. Run the project.

The answer is that the string wins. The result is the string, “22”. In this case the operator converts the number 2 to the string “2” and then “glues” it to the right “2” creating the string “22”. It seems confusing at first, but after you work with it a while, it will become second nature to you—promise!

Multiplication and Division

Now, look at the * and / operators for multiplication and division.

1. Replace the code in the timeline with the following:

// Math operators: Multiplication and Division
trace ( 2 * 3 );
trace ( 5 / 2 );

The first statement uses the multiplication operator, which is an asterisk, *. The division operator is a forward slash, /, and the order of the division is that it divides the value on the left by the value on the right.

2. Run the project; you’ll see the following in the Output panel:

6
2.5

Again, pretty simple stuff—but the next one will probably be new to you.

Modulo, the Operator Formerly Known as Long Division with Remainders

The modulo operator finds the remainder after a division operation. The modulo is quite helpful in many situations, including determining if a number is odd or even. Take a look at how it works.

1. Replace the code you have with the following, and take a look at the output:

// Math operators: Modulo
trace ( 5 % 2 );

2. Run the project; you’ll see the following displayed in the Output panel:

1

The % symbol invokes the modulo operator, finding the remainder after attempting a division of the value on the left with the value on the right. In this example, it divides 5 by 2, resulting in 2 and a remainder of 1. To see this written out in long division format, check out Figure 4.1.

Figure 4.1. 5 divided by 2 written in long division format, showing the remainder, or modulo.

image

Variables and Combined Assignment Operators

You’ll commonly want to complete a math function and assign the resulting value back to some named object, called a variable. ActionScript makes this easier by letting you combine arithmetic and assignment operators together. Take a look at an assignment operator example:

1. Create a new ActionScript 3.0 project and enter in the following code for the project:

// Assignment Operators
var myValue:Number = 2;
myValue = myValue + 2;
trace(myValue);
var myOtherValue:Number = 2;
myOtherValue += 2;
trace(myOtherValue);

2. Run the project. You’ll get the following in the Output panel:

4
4

Let’s walk through the code and explain how you get this result and what role variables and combined assignment operators play.

Variables

You haven’t really seen much about the var statement yet, so let’s reveal a little bit more about it. You have used it in the past to create named object containers that you have then assigned MovieClip symbols to using the new statement. You can also use var to create variables; in fact, variables is what var stands for. Variables are named objects that can contain variable values.

Take a look at the second line of the assignment operators example:

var myValue:Number = 2;

The var statement is creating a variable called myValue. See that :Number after the variable name? You have to tell ActionScript what type of data your variable can hold, similar to how you did when using the function statement. In this case, you are saying that myValue will contain a number. When you create the variable, it is empty, but when you assign the numeric value 2 to it, you can refer to that value using the name myValue.

myValue = myValue + 2;
trace(myValue);

On the second line above, you are accessing the myValue object and are assigning a new value to it. Notice that you are not using the var statement here, because var is only used to create a new variable. You don’t need to use it again if you are referring to a variable that has already been created. Before you assign the value, you need to complete the evaluation on the right side of the assignment operator. In this case, you are taking the existing value of myValue, 2, and adding the value 2 to it. This value is then assigned back to myValue, overwriting the existing value. In the last line of the first block, you send that value to the Output panel using the trace statement, which displays 4.

This completes the analysis of the first part of the code.

Combined Assignment Operators

Take a look at the second block of code. This section of code works identically to the first block, with two exceptions. In this section, you are creating a new variable called myOtherValue:

var myOtherValue:Number = 2;
myOtherValue += 2;
trace(myOtherValue);

In the first line, you need to use the var statement since you have not created that variable before. You then assign the numeric value 2 to it.

On the next line, you come across the first combined assignment operator, +=. This operator is combining addition with assignment. In this case it is taking the existing value of myOtherValue and is adding 2 to it and automatically assigning it back to the myOtherValue variable. Always put the arithmetic operator before the assignment operator. You can use this shortcut with any of the basic arithmetic operators:

// All combined assignment operators
var myValue:Number = 100;
myValue += 50; // 100+50 = 150
myValue -= 125 // 150-125 = 25
myValue *= 3   // 25*3 = 75
myValue /= 5   // 75/5 = 15
myValue %= 4   // 15%4 = 3
trace (myValue);

Programmers often use these combined assignment operators as shortcuts since they are nice time savers. Hopefully, you’ll find they are too!

Increment and Decrement Operators

When you work with ActionScript a lot, you’ll commonly be adding or removing 1 from variables and properties.

To make this process easier, there is a shortcut called the increment and decrement operators. Take a look at the following code.

1. Create a new ActionScript 3.0 project and enter in the following code for the project:

// Increment and Decrement
var myValue:Number = 5;
trace(myValue);
myValue++;
trace(myValue);
myValue--;
trace(myValue);

2. Run this project. You’ll see the following in the Output panel:

5
6
5

In the increment and decrement example, the value of myValue is initially set at 5 and is sent to the Output panel. The number is then increased by 1 and sent again, resulting in 6.

When you add a double minus, --, to the end, it decrements the value by 1. The value of myValue is already 6 based on the previous function, and is then decremented to be 5 again.

Order of Operations

By default, mathematical functions do not run from left to right, but follow a specific order of operations. You may recall from math classes that certain mathematical functions are calculated before others, regardless of their left-to-right order.

1. Create a new ActionScript 3.0 project and enter in the following code for the project:

// Order of Operations
var answer:Number = 2 + 3 * 2 / 4 - 1;
trace(answer);

In this example, you have a number of math functions that are running from left to right. If you don’t follow the order of operations and evaluate it from left to right, you get 1.5, as shown in Figure 4.2.

Figure 4.2. Incorrect left-to-right order of operations

image

2. Run the code. You’ll see what might seem unexpected: 2.5. Why? Because certain math functions are executed before others. In fact, this is the order:

1. Multiplication, Division, and Modulo

2. Addition and Subtraction

All the multiplication, division, and modulo operations are processed from left to right to the end. Then calculation starts again from the left and processes addition and subtraction. Look at Figure 4.3 to see how this works.

Figure 4.3. Correct order of operations for the evaluation

image

When the Flash runtime looks at the ActionScript, it starts from the left, evaluating the expression:

• It ignores the 2 + 3, since the rules dictate processing only multiplication, division, and modulo at this point.

• 3 × 2 = 6 image

• 6 / 4 = 1.5 image

Since there are no more multiplication, division, or modulo operations, it returns to the beginning and processes addition and subtraction.

• 2 + 1.5 = 3.5 image

• 3.5 - 1 = 2.5 image

You have the final result, 2.5 image, which is then sent to the Output panel.

You can alter the order of operation by using parentheses. This will force Flash to adopt a specific path of calculating the results. You’ll learn about overriding the order of operation rules in the next section.

Using Parentheses to Force Order

You can force the earlier example to follow the order of operation that results in the value of 1.5. You can use parentheses to group calculations together. In the order of operations, math operations that are grouped within a pair of parentheses are always calculated first.

You can adjust the example to get the 1.5 that you originally calculated by performing the calculations from left to right:

// Order of Operations
var answer:Number = (2 + 3) * 2 / 4 - 1;
trace(answer);

Now instead of skipping the first addition action, the Flash runtime calculates what is inside the parentheses first and then continues across, as shown in Figure 4.4.

Figure 4.4. Forcing the order with parentheses using order of operations

image

When the Flash runtime looks at the ActionScript, it starts with the first set of parentheses it finds:

• 2 + 3 = 5, which is the only set of parentheses image

It then starts back at the beginning with multiplication, division, and modulo:

• 5 × 2 = 10 image

• 10 / 4 = 2.5 image

Now that it is finished with multiplication, division, and modulo, it starts back on the left and evaluates addition and subtraction:

• 2.5 - 1 = 1.5 image

You end up with 1.5 image, which is then sent to the Output panel.

You can nest parentheses within each other, but just make sure that every opening parenthesis has a matching closing parenthesis. This is one of the most common bugs you’ll find in your programs, unmatched parentheses and braces.

Summing up Math Operations

You have covered a lot of math in this chapter, but more importantly, you were able to expand your knowledge of working with numbers and variables and start doing some calculations with them. Table 4.1 will serve as a handy reference for the operations that were covered in this chapter:

Table 4.1. Mathematical Operators

image

Wrapping Up

In this chapter, you learned the basics of working with variables and how to change numeric values using arithmetic operators in ActionScript. You also learned some of the common shortcuts advanced programmers use to save time when working with math operators, including working with combined assignment operators and the increment and decrement operators.

When working with operators in ActionScript, keep the following in mind to avoid common pitfalls and errors:

• When creating a variable and referring to it the first time, you need to use the var statement to create it. You can then refer to it without the var statement afterwards.

• When using the + operator, be sure to not inadvertently mix up strings and numbers, as strings will concatenate and ignore the numeric values.

• The modulo operator calculates the remainder after attempting to complete an even division.

• If you are working with a combination of multiplicative (multiplication, division, or modulo) functions and summation (addition or subtraction) functions, remember that ActionScript will evaluate your equation using mathematical order of operations.

• To quickly modify an existing value based on a function, you can use combined assignment operators to save time.

• If you are adding or subtracting 1 to or from a value, you can use increment or decrement operators, using ++ or -- as a quick shortcut.

• To force the order of operations to do something specific, you can use parentheses to group evaluations you want to process first.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.140.206