Creating Variables


In this lesson, you were introduced to the concept of ActionScript, saw its basic syntax, and were teased with a few lines of code. Now it's time to start learning how to write some ActionScript yourself! It all starts with understanding variables and how to create them.

When creating an application there are many pieces of data that need to be managed. For instance, a Visit Website button would take a user to a specific website after the click. The URL of this destination website needs to be stored somewhere in the application so the ActionScript for that button knows where to take the user after clicking. A variable is needed in that situation. Here is an example script:

   var destinationWebSite:String = "http://www.electrotank.com";    visitWebsite_btn.onRelease = function() {    getURL(destinationWebSite);    }


The function getURL is built into the Flash player. It launches a new web page when a user clicks and then releases the button. As you can see in the preceding example, variables are used to store data. The first line of code creates a new variable called destinationWebSite. The next few lines capture the onRelease event of a button and execute the getURL function as a result. As you can see in the third line of the code, the destinationWebSite variable is fed into the getURL function. The getURL function looks at the value of this variable, sees that it is http://www.electrotank.com, and then opens a new web page to that URL.

Variables can be used to store any type of data available in Flash. There is no reasonable limit to the number of variables that you can use in your application. Some types of variables are useful to be created and destroyed as the application progresses, and some you'll want to stick around the whole time. Through the course of this book, you'll encounter these situations and gain experience working with variables in a number of ways.

You'll see how to create variables and the types of data that they can store in the next section.

The Syntax

If a line of ActionScript is a sentence telling the application what to do, then operators (=, +, -, etc.) are verbs, and variables are nouns. A variable is a named reference to a piece of data. For instance:

   var firstname:String = "Jobe";


The name of the variable is firstname. The data, also known as the value of the variable, is "Jobe". Notice that :String appears after firstname. This is called data typing and will be discussed in the next subsection.

To create a new variable, first type the characters var and then add a space. This tells the Flash player that you are declaring a new variable. Then type a name for that variable this is your choice. After the name, you can strictly type the variable by typing a colon and then the data type (discussed as follows). Next, you need to assign the variable a value, which is done using the assignment operator (=). Following the =, you type the data that you want to store. And as with all other actions, it ends with a semicolon.

When declaring a variable properly, you are telling the Flash player three things:

  • Its existence. You inform the Flash player that from this point forward, within the current scope, a variable with this specific name will exist. Scope is something that will be discussed more in Lesson 2, "Functions."

  • Its scope. As mentioned previously, we will discuss scope more in Lesson 2. For now, it's enough to understand that a variable can be created but seen only in certain areas. For instance, the variable firstname can appear with different values in many areas of the application.

  • Its data type. Data types will be discussed in the next subsection. A variable can store a name, such as "Jobe," but can also store numbers, dates, and many other types of data. As you'll see, it is to your advantage to define a variable's data type.

The value of a variable doesn't have to be typed in. You can have the value of the variable driven dynamically by the values of other variables. That is the power of ActionScript! Here is an example:

   var firstname:String = "Jobe";    var welcomeMessage:String = "Good morning "+firstname+"!";


In this example, two variables were created. The first one, firstname, stores a name. The value of the second variable, welcomeMessage, is dynamically generated based on the value of firstname. In this case, the final value of welcomeMessage is Good morning Jobe!

Data Types and Strict Data Typing

Variables store data, which can be text (such as the name of a city), a number (such as the age of a person), and so on. These different types of data are called data types. When declaring a variable, it is recommended to also assign it a data type, which is strict data typing. Strict data typing is a simple concept.

   var variableName:DataType = someValue;


You have seen the preceding syntax several times in this lesson. Strict data typing comes into play in the syntax after the variable name. It is the :DataType part. Let's start with a few lines of code and then explain them:

   var catName:String = "Anna";    var ageInYears:Number = 3;    var ageInMonths:Number = ageInYears*12;    var isSpayed:Boolean = true;


In this example, four variables were created using three different data types. The first one is a String, which is data that should be treated as text. The second variable is typed as a Number, which is a type of data that stores an actual numeric value. The value "3" is a String, which is different from 3. One is treated as text, and the other is treated as a number. The third line of ActionScript is typed as a Number as well. Notice that this variable's value is set by the product of two other numbers.

The final line of ActionScript types the variable isSpayed as a Boolean. If you are completely new to programming, the concept of a Boolean value is probably new to you as well. A Boolean value is either true or false, and that is it. It cannot contain any other values. They are used to store information that can have only two states. As an example, you might store a value in your application that indicates whether the user has logged in or not. You might call this variable isLoggedIn. If its value is true, the user has logged in; otherwise, it's false.

In addition to String, Number, and Boolean, dozens of other data types are used in ActionScript. In fact, as you learn how to build your own custom classes (see Lesson 6, "Custom Classes"), you'll see that you create your own custom data types!

Note that data typing is not required. You can leave off the :DataType part of your variable declaration. Before you abandon strict data typing, however, please read the rest of this section to see why it's so important. We'll use strict data typing throughout this book.

Now you should understand the how of data typing. But because data typing is not required, you might wonder why should I data type? There are a few very compelling reasons why you should data type. These reasons are very important even if they might not seem so to the novice programmer.

  • Workflow. When you work on an application, you'll very quickly reach dozens, hundreds, or even thousands of lines of code. When adding to your code or revisiting it months later, you'll thank yourself for properly declaring variables with a data type. This gives you more information about a script that you are looking at than you would normally have. The combination of commenting your code and data typing variables will help your workflow or a coworker's stress level as code enhancements are needed.

  • Compile-time errors. This is huge. Strict data typing can happen in areas of your script that we haven't yet discussed. You'll see more about this in a later lesson. If you data type in every area of your code that allows data typing, then when you publish or test your SWF file, the compiler will perform a certain level of error checking for you. For instance, consider this:

    var catName:String = "Anna"; var age:Number = 3; var ageInMonths:Number = catName;

    In the third line of the preceding script, the variable was declared as a number. But we tried setting its value from a variable that was declared as a String. If this script was in your Flash application and you tried to publish or test the SWF file, you would receive an error. The previous example is extremely simplified. As you create more-complex scripts, you'll find the fact that you receive an error a good thing. It's better to be told that there is an error while you are creating the application, than to let the SWF be published as "error-free," only to find the bug at some later date.

  • Code hints. If you strictly type a variable, you can gain access to code hints as you use that variable. We haven't yet discussed classes, methods, or properties. But for now, it's enough to know that by strictly typing a variable, you can make your life a little easier. With code hints, the Actions panel can predict certain things for you as you type. Code hints are automatically shown for a variable in a drop-down list if you type a period (.) after the variable in a line of code.

In this section, you learned the syntax used to properly create a variable. In this exercise, you will create some variables and will use strict data typing.

1.

Open Navigation1.fla in the Lesson01/Start folder.

This application is a very basic Flash website navigation example. There are three buttons that are used to navigate between three frames. Variables will be used to dynamically size the logo and to display a welcome message on the home page screen. The three buttons will be made interactive to handle navigation.

There are seven layers in this file. The first layer is called labels. Frames are numbered, but they can also be labeled. Using ActionScript, you can tell the movie to go to a specific frame number or to a frame label. This movie has three frame labels in this layer: Home Page, News, and Contact Us.

As with the previous exercises, an actions layer holds the ActionScript. The three buttons, homePage_btn, news_btn, and contactUs_btn, are on the nav buttons layer. The logo for the website, which is large and seen in the upper-left corner of the Stage, is contained on the logo layer. It has an instance name of logo_mc.

The nav bar layer contains the graphic for the navigation bar, and the background layer contains the graphic for the background image. The content layer contains the content that is frame-specific. There are three key frames, one for each frame label. On the Home Page label, there is a text field with an instance name of welcome_txt. On the other content frames, there is only static text.

2.

Click Frame 1 in the actions layer. Open the Actions panel by selecting Windows > Actions or by using the hotkey F9.

You just opened the Actions panel. There is not yet any ActionScript on this frame. If you have Script Assist enabled from the previous exercises, make sure that you deselect that option. In this exercise, you'll be typing directly into the Script pane.

3.

Add a stop action to the Script pane. Type this: stop();

A SWF file that has more than one frame will automatically play. If you were to test this application before adding a stop action, you would see the movie jump from content screen to content screen as the movie plays continuously through all of the frames.

A stop action tells the Flash player to stop playing through the current Timeline. You will use stop actions very frequently to ensure that your application flow is controlled by ActionScript, not just by animation.

4.

On the next line, declare a new variable called logoScale, type it as a number, and give it a value of 55.

So, enter this ActionScript:

   var logoScale:Number = 55;


You probably noticed that the logo doesn't fit nicely within the navigation bar; it is just too large. Using ActionScript, we'll make the logo movie clip smaller to fit within the navigation bar.

You just created a variable called logoScale. We will use the value of this variable to assign a new size to the logo_mc movie clip instance.

5.

To size the logo_mc instance, add these two lines to the script:

   logo_mc._xscale = logoScale;    logo_mc._yscale = logoScale;


Movie clips have a property called _xscale. This property contains the percentage of the movie clip's current width, as compared with its natural width. Movie clips are not resized, so the _xscale value would be 100, because its width is 100 percent of the natural width.

You can set this property, as is done in the first line that you added previously. By adding that line of ActionScript, you are telling the logo_mc movie clip instance to change its width to 55 percent of its natural width. It is 55 percent because the value of logoScale is 55.

The second line of code you added does the same thing as the first, but for the _yscale property. The end result is a movie clip that has scaled to 55 percent of its original size.

6.

Next, create a new variable called welcomeMessage, type it as a string, and give it a string value of "Welcome to Science Now!". Then populate the welcomeMessage_txt field with this value.

To do this, type these lines of ActionScript,

   var welcomeMessage:String = "Welcome to Science Now!";    welcomeMessage_txt.text = welcomeMessage;


Here you have created a new variable called welcomeMessage. It contains a string that will be displayed in the welcomeMessage_txt text field.

In the previous step, you changed the value of the _xscale property of a movie clip to alter the way it looks. In this step, you are changing the value of the text property of a text field to alter the way it looks. The act of assigning a new value to this text property displays it on the screen within that text field.

You have now created and used all the variables that are needed for this exercise. The rest of the steps deal with something you have done before: capturing the onRelease event of buttons.

7.

Add button event handlers to capture the onRelease event of the three button instances. In each event handler, add a gotoAndStop action to send the movie to the appropriate frame label.

To do so, add this code

   homePage_btn.onRelease = function() {      gotoAndStop("Home Page");    };    news_btn.onRelease = function() {      gotoAndStop("News");    };    contactUs_btn.onRelease = function() {      gotoAndStop("Contact Us");    };


In the previous exercise, you added onRelease event handlers to buttons using Script Assist. Here you get a chance to type them using the correct syntax. Events and event handlers will be discussed in greater detail in Lesson 7, but you will also learn more about them along the way.

The gotoAndStop global function sends the current Timeline to a specific frame. You can feed it a number or a frame label string value. In this case, you are using frame labels.

8.

Test the movie by selecting Control > Test Movie, or by pressing Control + Enter. Notice the welcome message and the size of the logo. Click the navigation buttons to check your work.

The welcome message should be displayed on the home page. The logo movie clip shows on all content frames. When you jump from the home page to another screen and then back to the home page, the ActionScript on that frame is again executed. If it were not executed again, the welcome message wouldn't show up when you leave the home page and then come back.

9.

Close and save your work as Navigation2.fla.

In this exercise, you created variables to store values. You then used those values to manipulate the way the application displays.




Macromedia Flash 8 ActionScript Training from the Source
Macromedia Flash 8 ActionScript: Training from the Source
ISBN: 0321336194
EAN: 2147483647
Year: 2007
Pages: 221

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