Variables


Now that we have covered data, let's take a look at what holds this data, variables.

Data without variables only lives for a second; once the interpreter has passed it, its lifespan is over. Variables are like Tupperware: They can hold data for long periods of time, and whenever you want that data, you just go to the variable and it's still there. A variable can hold any type of data, including strings, numbers, Boolean values, and even other variables.

A downside to variables is that they can only hold one piece of data. Arrays, on the other hand, can hold multiple pieces of data (see Chapter 10 for more information).

Making a Variable

A variable can be created in several different ways. Let's start with the easiest method, which is the one we will be using most often. You simply use the keyword var to start the process, name the variable, and finally assign it a type. You close the line with a semicolon so that the interpreter knows the line has finished. Here's an example:

 var myVariable_str:String; 

That's easy enough. Now let's do the same thing, but this time assign it some data:

 var myVariable_str:String = "Unleashed"; //we set myVariable_str to the string literal "Unleashed" 

Although it is possible to create variables without setting the data type, it is good practice to assign the data type when the variable is created. Also, after you declare the data type, you cannot change the type of data being held within the variable without receiving an error.

You do not actually need the keyword var to declare a variable (although the code is easier to follow when you're looking through it, and you cannot declare a data type without the keyword var); the interpreter will recognize that a variable has been declared when data is assigned. Here's an example:

 myVariable_str = "Unleashed"; //we still declared a variable, but without the keyword var 

Another way to declare a variable is by using the set action. In the parentheses, you declare the variable's name with a string literal and then set its value after a comma:

 set ( "myVariable", 6 ); trace (myVariable); // output: 6 

We have looked at assigning variables with single pieces of data; now let's look at one assigned with an expression:

 var myVariable:Number = 2+4; trace (myVariable); // output: 6 

This time, we are going to assign the value of a variable to another variable:

 var myVariable_str:String = "Unleashed"; var variable2_str:String = myVariable_str; trace (variable2_str); // output: Unleashed 

You can create multiple variables with the same data using equality marks to separate them, as shown here:

 var myVariable_str:String = variable2_str = variable3_str = "Unleashed"; trace (myVariable_str); trace (variable2_str); trace (variable3_str); // output: Unleashed //         Unleashed //         Unleashed 

Even though each variable has the same value, the last two variables are not bound by the data type, and can be changed without an error popping up, but it is good practice to not change the data type of variables during runtime.

You can even assign a variable to an expression using other variables:

 var myVariable:Number = 4; var myVariable2:Number = 2; var addedVariables:Number = myVariable + myVariable2; trace (addedVariables); // output: 6 

Changing Data in Variables

Now that you have seen how to create variables and add data to them, let's see how to change the data in them.

The process is as simple as reassigning data to the variables:

 var myVariable_str:String = "Unleashed"; trace (myVariable_str); myVariable_str = "Flash"; trace (myVariable_str); // output: Unleashed //         Flash 

Another way to change a variable is to add to it. Here's an example:

 var myVariable_str:String = "Flash"; trace (myVariable_str); myVariable_str = myVariable_str + " Unleashed"; trace (myVariable_str); // output: Flash //          Flash Unleashed 

Here, all we did was set the variable equal to itself plus another string. There is an easier way of doing thisby using an assignment operator, called the addition assignment operator (+=).

We'll use the same code as before but replace the long, written method of adding additional text with this new way:

 var myVariable_str:String = "Flash"; trace (myVariable_str); myVariable_str +=  " Unleashed"; trace (myVariable_str); // output: Flash //         Flash Unleashed 

Now let's look at another variable that uses an incremental operator to increase its value.

Incrementing and Decrementing Variables

As you have just seen, you can add to already created strings. Now let's look at how to do it with numbers.

First, create a new Flash document, and then open the Actions panel on the first frame of the main timeline and place the following code in it:

 //let's create our variable var i:Number = 0; //this event will continue to run this.onEnterFrame=function(){ //let's increase our variable one at a time     i = i + 1;     trace (i); } // output: (it will start with 1, and increase by 1 constantly) 

That was the old way of adding to variables; now let's do it the new way:

 //let's create our variable var i:Number = 0; //this event will continue to run this.onEnterFrame=function(){ //let's increase our variable one at a time     i += 1;     trace (i); } // output: (it will start with 1, and increase by 1 constantly) 

That looks better, but there's still an easier way to increase a variable by one each time, and that's by using the increment operator (++):

 //let's create our variable var i:Number = 0; //this event will continue to run this.onEnterFrame=function(){ //let's increase our variable one at a time     i++;     trace (i); } // output: (it will start with 1, and increase by 1 constantly) 

That was great! However, if we want to increase our variable by more than one at a time, we'll have to go back to the addition assignment operator because the increment operator only increases at a rate of one at a time.

Now that we have these numbers, let's make them move a movie clip to the right. So now create a small circle on the left of the stage and convert it to a movie clip symbol by selecting the fill and the stroke and going to Modify > Convert to Symbol. When the Convert to Symbol window pops up, set Movie clip as the behavior and leave everything else at the default settings and hit OK. Then back on the stage, give the circle an instance name of circle_mc in the properties inspector, and finally, make this change to the actions: (More on movie clips in Chapter 13.)

 //let's create our variable var i:Number = 0; //this event will continue to run this.onEnterFrame=function(){ //let's increase our variable one at a time     i = i + 1;     circle_mc._x = i; } // output: (it will start with 1, and increase by 1 constantly) 

Now when you test the movie, the little circle will move to the right one pixel at a time.

Technically, you could have written the preceding code like this:

 this.onEnterFrame=function(){        circle_mc._x++; } 

We've covered increment variables, so now let's review decrement variables. These variables are the exact opposite of increment variables because they take away one at a time.

Let's look at our previous code with the circle move clip. Using the same code, replace instances of ++ with , which will cause the variable to decrease:

 //let's create our variable var i:Number = 0; //this event will continue to run this.onEnterFrame=function(){ //let's decrease our variable one at a time     i;     circle_mc._x = i; } 

Now the circle moves to the left one pixel at a time.

Empty Variables

As you know from previous sections, an empty variable has a value of undefined. We can use this to test whether a variable is being used. We use an if statement to test whether a variable is equal to undefined; if it is, the variable needs to be filled. Let's take a look at an example:

 var title_str:String; if (title_str == undefined) {        trace ("This variable is empty"); }else{        trace ("This variable has information in it"); } // output: This variable is empty 

Because the variable we created has yet to be assigned any data, it is automatically valued as undefined and the if statement value is TRue.

Comparing Variables

Often, when using variables, you'll want to compare one against another (for password verification, memory games, and high score validation, for example).

When you're comparing variables, it's important that they are the same data type. Keep that in mind until we get to the next section.

Let's start with a password-verification example. We'll use a predefined password and a user input password and compare them. If they are equal, we'll run some specific code; if they are not equal, we'll run different code. Here are the steps to follow:

1.

Start a new file by going to File, New and then choosing Flash Document.

2.

Create two more layers on the main timeline and label the layers Actions, Input, and Validate, respectively top to bottom.

3.

Now create a movie clip symbol called "validate" that has a rectangle in it with the text "Validate" over top of it. Place this movie on the Validate layer of the main timeline and label its instance name validate_mc.

4.

In the Input layer, choose the Text tool and draw a text box. Change the type in the properties inspector to Input Text and choose Show Border Around Text so you can easily see the text box when we test the movie. Then choose Password for the line type instead of Single Line (this will place asterisks instead of characters in the text box). Finally, give the text field an instance name of password_txt. The settings should look like Figure 9.2.

Figure 9.2. The stage for the validate example.


5.

Now for the actions. In the first keyframe of the Actions layer, place this code:

 //We first create the password var password_str:String ="flash"; //Now we set the button actions for the validate movie validate_mc.onRelease = function (){ //this will check to see if the password and the input match     if(password_txt.text == password_str){         trace("You may enter");     }else{         trace("You do not have clearance"); //This clears the input field         password_txt.text="";     } } 

When you test the movie, note that if you enter the correct password, it issues a welcome message in the Output panel; otherwise, the Output panel displays a different message and clears the user input field.

As another example of using variables, let's try to determine whether a new score is the high score.

Create a new file as before in previous examples (PCCtrl+N, MacOpen Apple+N) and put the following code in the first frame of the main timeline:

 //first create the current high score var highScore:Number = 1200; //then create a new score to rival the high score var newScore:Number = 1300; //now create the if statement that will determine and adjust the high score if (newScore > highScore){     highScore = newScore;     trace ("congratulations, the new high score is " + highScore); }else if (newScore == highScore) {     trace ("You are now tied for 1st at " + highScore); }else{     trace ("Your score of " + newScore + " was not good enough"); } // output: congratulations, the new high score is 1300 

Test the movie. Then go back and change the variables to see different results.

Combining Types of Values in Variables

You may have noticed in the preceding high-score example that we were adding two different types of values into one statement. So, what does that make the value of the statement? That depends on what was combined and how. Because in the preceding example we added a string with text in it to a number, the interpreter automatically converted the entire thing to a string.

Now let's take a look at using the typeof function to check the value of a given variable:

 var name_str:String = "Kevin "; var age:Number = 35; var combined_str:String = name_str + age; trace (typeof(combined_str)); // output: string 

Let's suppose we have two variables (one a number and the other a string containing numbers):

 var year_str:String = "1967" var age:Number = 35; var combined_str:String = year_str + age; trace (typeof(combined_str)); // output: string 

This still comes back as string. However, if we subtract them, the result changes, as shown here:

 var year_str:String = "1967" var age:Number = 35; var combined:Number = year_str - age; trace (typeof(combined)); // output: number 

When the variables are subtracted, the interpreter converts the combination to a number.

Although the conversion has taken place in the combined variable, it has not affected the original values. Automatic conversion only works when evaluating an expression.

When using a Boolean in an expression involving a number, the conversion will always be to a number, as shown here:

 var answer:Boolean = true; var age:Number = 35; var combined:Number = answer + age; trace (typeof(combined)); // output: number 

The same goes for a Boolean and a string. Both data types will always convert to a string:

 var answer:Boolean = true; var age_str:String = "35"; var combined_str:String = answer + age_str; trace (typeof(combined_str)); // output: string 

As far as conversion goes, what does the interpreter convert each element to? To find out, let's take a look at the next few lists.

These rules apply to string conversions:

  • A number converts to a string literal equal to that number (for example, 123 to "123").

  • A Boolean converts to true if true and false if false.

  • Undefined converts to undefined.

  • Null converts to null.

  • NaN converts to NaN.

  • An array converts to a list of elements separated by commas.

These guidelines apply to number conversions:

  • A string containing numbers converts to a numeric value represented in those numbers.

  • A string not containing numbers converts to NaN.

  • Undefined converts to NaN.

  • Null converts to NaN.

  • A Boolean converts to 1 if true and 0 if false.

  • NaN converts to NaN.

  • An array converts to NaN.

These are the rules for Boolean conversions:

  • A string with a length greater than 0 converts to TRue.

  • An empty string converts to false.

  • A number converts to TRue if it's a nonzero number and false if it's zero.

  • Undefined converts to false.

  • Null converts to false.

  • NaN converts to false.

  • An array converts to true.

Converting Variables Using Functions and Methods

Now that you know what values convert to, let's see how to convert them. We will start the conversions by using the toString method. Remember, you are only converting the data type within the variable to another data type, not the variable itself.

The toString Method

This method acts like any of the previous methods we've discussed. Simply attach it directly to a data type you would like to convert to a string or attach it to a variable you would like to convert. There are no arguments in the parentheses. Here's an example:

 var age:Number = 35 var myString_str:String = age.toString();       //Converts the variable age to a string var myString_str:String = false.toString();     //Converts the boolean datatype false to a string var myString_str:String = (50).toString();      //Converts the number 50 to a string // the parentheses are there so as not to // confuse the interpreter into //thinking it was a decimal point 

The String Function

To use the String function, simply place the variable or data type you would like to convert in the parentheses, and the function will convert it to a string:

 var myString_str:String = String(myVariable); var myString_str:String = String(123); var myString_str:String = String(null); // the String function converts all of these datatypes to a string datatype 

Using Operators

You have already seen that using a plus sign (+) will convert numbers and variables to a string, as shown here:

 var myString_str:String = 500 + "string";       //Converted to a string var myString_str:String = myVariable + "";      //Using an empty string to convert variables to a string 

The Number Function

This function acts nearly identically to the String function. Place the variable or data you want to convert in between the parentheses, and the function will convert it to a number:

 var myNum:Number = Number(myVariable);      //Converts value of myVariable to a number var myNum:Number = Number("Unleashed");     //Becomes NaN var myNum:Number = Number("1234");          //Becomes the number 1234 

This function is great for converting input fields that are string literals such as ZIP codes or age.

The parseInt and parseFloat Methods

These methods convert strings to numbers much like the Number function. However, unlike the Number function, these two methods can pull numbers out of text, as long as the first nonspace character is a number.

Let's take a look at the parseInt function, which is for pulling whole integers (remember from earlier, integers have no decimals or fractional values). Just call this function as you would any other function and place the variable or string you want to convert in the parentheses:

 var idNumber_str:String = "123abc"; trace (parseInt(idNumber_str)); // output: 123 

The parseFloat function works in much the same manner, but it pulls floating numbers instead of integers:

 var idNumber_str:String = "123.487abc"; trace (parseFloat(idNumber_str)); // output: 123.487 

If the first nonspace character is anything but a numeric value, the function returns NaN:

 var idNumber_str:String = "abd123.487"; trace (parseInt(idNumber_str)); // output: NaN 

In case you're wondering what happens when you use parseInt on a floating number, the following example shows that the function will return everything up to the decimal point:

 var idNumber_str:String = "123.487abc"; trace (parseInt(idNumber_str)); // output: 123 

However, if you use the parseFloat function on an integer, it will return the same value as the parseInt function:

 var idNumber_str:String = "123abc"; trace (parseFloat(idNumber_str)); // output: 123 

The Boolean Function

Converting to a Boolean is as easy as using the String or Number function. Place the variable or data type in the parentheses, and the Boolean function converts it to a Boolean:

 var mySample:Boolean = Boolean(myVariable);     //Converts the value of myVariable to Boolean var mySample:Boolean = Boolean(123);            //Converts to true var mySample:Boolean = Boolean(0)               //Converts to false 

The Scope of a Variable

So far, we have placed variables on the main timeline and in a movie on the main timeline. It's now time for you to learn about the scope of variables and how to overcome the shortcomings of the local scope of variables.

Timeline Variables

Whenever a variable is created or defined on a timeline, it is available to every frame on that timeline as well as any buttons that have been placed on the stage associated with that timeline.

Any code placed in the object actions of a movie clip instance can access variables on the timeline of that movie, but not the timeline the movie is in. Here's an exercise to make this clear:

1.

Start a new file as you did before.

2.

On the main timeline, place the following code:

 var myVariable_str:String = "Success"; 

In the second frame of the main timeline, place this code:

 //this will stop the movie from looping stop(); trace (myVariable_str); 

3.

Now create a new layer called rectangle and place a rectangle on that layer. Highlight the rectangle and press F8 on your keyboard to convert it to symbol (or select Modify>Convert to Symbol). Then choose Button as the behavior. And give this button an instance name of myButton_btn.

4.

Go back into the actions of the first frame, and place these actions in:

 myButton_btn.onRelease=function(){     trace(myVariable_str); } 

You're done, so test it.

You should see the word Success pop up in the Output window, and when you click the rectangle button, the variable should appear again (see Figure 9.3).

Figure 9.3. A successful implementation of a timeline variable.


Dot Syntax

Dot syntax enables code to see from one timeline to the next, either by direct route with the use of instance names or with special predefined identifiers such as _root and _parent. Just remember that each level must be separated by a dot, hence dot syntax.

The _root and _parent identifiers are constants: _root is always the main timeline and will never change (however, you can define the _root of a movie clip using the _lockroot property of a movie clip), but _parent is relative to where you are using it, and it always goes up one level in hierarchy.

Another part of dot syntax involves using the instance names of symbols. For example, if you want to know the horizontal position of myMovie_mc on the main timeline, you would type the following:

 _root.myMovie_mc._x; 

If you need to know the value of myVariable in the movie myMovie_mc, which is embedded in theMovie_mc, which in turn is on the main timeline, you would use this:

 _root.theMovie_mc.myMovie_mc.myVariable 

The _root Identifier

The _root identifier represents the main timeline; everything on it can be accessed like so:

 _root.whatever 

Let's look at an example of this:

Create a new Flash file like before.

Create a second layer, and name the layers Actions and Content.

On the main timeline, in the Content layer, create a movie clip with these actions on its timeline:

 trace (theVariable_str); trace (_root.theVariable_str); 

2. On the main timeline in the first frame of the Actions layer, place this code:

 var theVariable_str:String = "theRoot"; 

Now test the movie again. Here's the output:

 // output: undefined //         theRoot 

The movie came back with undefined because the variable could not be found in its local scope, but using _root, it found the variable with ease.

The _parent Identifier

The _parent identifier is used in dot syntax to refer to one step up. Parents can be overlapped like this:

 _parent._parent 

Now go back into the actions of the movie you created earlier and replace its code with the following:

 trace (_parent.theVariable); 

Now test again:

 // output: theRoot 

This time, the _parent part of the dot syntax looks up one level and finds the variable.

Although this may seem tedious and difficult to understand, thanks to the _global identifier, many of these problems can be solved.

The _global Identifier

Introduced back in Flash MX, the _global identifier creates data types that can be seen from all parts of the Flash movie without the use of dot syntax and target pathing.

Just attach the _global identifier to what you would like to make global; then you can access it from anywhere in the Flash movie.

1.

Start a new Flash movie. Then on the main timeline, in the first frame, place this code:

 _global.myVariable = "Omnipotent"; 

2.

On the stage, draw a rectangle and convert it to a movie clip symbol (F8) with the symbol name draw1.

3.

Convert it again, this time with the symbol name draw2.

4.

Convert it for a third time, with the symbol name draw3.

5.

Open up your library (PCCtrl+L, MacOpen Apple+L) and go into draw1. In the first frame of the timeline, place the following code:

 trace (myVariable); 

Now test the movie:

 // output: Omnipotent 

Is that powerful or what? You have just traced a variable on the main timeline from another timeline that is embedded into three separate movies.

If you happen to create a local variable with the same name, only ActionScript attempting to access it locally will be affected; it will not affect the global variable.

The this Identifier

The this identifier is used to refer to the current timeline, or object it is being placed in. It acts in the same way the understood "you" does in English. To better understand the this identifier, here is an example:

1.

Create a new Flash document.

2.

Draw a circle about 50x50 in size on the left side of the stage.

3.

Convert it to a movie clip with the symbol name circleMC.

4.

Back on the stage, give the circle an instance name of circle_mc in the properties inspector.

5.

Add a new layer called actions and place this code in the first frame of that layer:

 //this variable is placed on the main timeline this.myTime = getTimer(); //this event is for a movie clip on the main timeline circle_mc.onEnterFrame=function(){      //this variable refers to the timeline of circle_mc      this._x += 1; } 

The this identifier is not necessary in most cases, but it is good practice to use it to make it easy when going back over code to see which timeline or object it is referring to.

An Applied Example

You have learned a lot of fun stuff in this chapter (and some not-so-fun stuff). Let's end with an easily applied example of how to use variables. Follow these steps:

1.

Start a new Flash movie and make its dimensions 400x400 in the stage properties.

2.

Now draw a circle on the main stage, but not too bigabout 50x50 should do. Convert this circle to a movie clip symbol. Then give it an instance name of circle_mc.

3.

Create a new layer called actions, open the Actions panel in the first frame of that layer, and then put these actions in:

 //create all our variables var friction:Number = .5; var pointX:Number = Math.round(Math.random()*400) var pointY:Number = Math.round(Math.random()*400); //create the event this.onEnterFrame=function(){ //set our if statements to move at different speeds //based on distance, and to pick a new spot once the //designated spot has been reached     if (Math.round(circle_mc._x) != pointX){          circle_mc._x+=(pointX-circle_mc._x)*friction;     }else if (Math.round(circle_mc._x) == pointX){           pointX = Math.round(Math.random()*400);     }     if (Math.round(circle_mc._y) != pointY) {           circle_mc._y+=(pointY-circle_mc._y)*friction;     }else if (Math.round(circle_mc._y) == pointY){           pointY = Math.round(Math.random()*400);     } } 

Now test the movie.

In this example, the if statements are saying that if the object is not at its designated spot yet, adjust its position based on the distance it is from the designated spot. Then, once it has reached the spot, pick a new spot and keep moving the circle.

Note that you can adjust the friction to achieve some interesting effects.




Macromedia Flash Professional 8 Unleashed
Macromedia Flash Professional 8 Unleashed
ISBN: 0672327619
EAN: 2147483647
Year: 2005
Pages: 319

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net