0

   

Introduction to variables and data types in actionscript 2.0

In previous tutorial you learned how to control the timeline with simple actiosncript commands. Now you’ll learn what variables are.

Basically, variables are data containers. Their main function is to store data to be retrieved later.

It is denoted by a variable name followed by a piece of data. For instance,

speed = 10;

These variables can be a constant (unchanging). They can also be frequently changed. For instance, a variable that stores the score of a football video game would increase every time the player scores a goal.

A variable’s data can be retrieved as many times as you want. For instance, in a game, you store your player’s name in a variable. When you’re talking to an NPC (non player character), he mentions your name by recalling the data inside the variable.


Strict data typing

Strict data typing was introduced in Flash MX 2004. It requires a user to clearly define the data type of a variable. Some common data types a variable can store are strings, numbers, boolean, arrays and objects. In addition, the variable starts with a var. Below are some sample variables in accordance to strict data typing.

var score:Number =10;
var playerName:String= “hero”;
var dead:Boolean =true;

However, it is completely optional to use strict data typing. Flash forgives you even if you don’t want to use this style of programming.

Yet, using the “proper” syntaxes develops a good habit that aids you when learning other programming languages like Java.

Still, personally, I like to define a variable like this:

var identifier = data;

It is also acceptable to use

identifier = data;

However, for optimization purposes, placing a “var” in front of a variable is a better practice. Studies show that it could slightly speed up actionscript execution.


Primitive data types

To clarify, in Flash, there are 3 types of primitive data a variable can store: string, number and boolean.

String

Strings are text. For instance,

var nickname = “simon”;

“Simon” is the string contained by the “nickname” variable. Note that a string’s data must be enclosed by “ ” to be recognized by Flash. Even if you type in numbers to a string variable, it is considered as text, not numbers.

Number

A number variable can be used to perform mathematical operations. For instance, I can compute the sum of the 2 variables below.

var attack = 1;
var damage = 2;
trace (attack+damage);

The result displayed would be 3.

Boolean

A Boolean variable only stores 2 types of data’s, true and false. For instance,

var unlocked = false;

This type of variable is useful for triggering events. For example, take a look at the script below.

If (unlocked == true) {
trace(“door opens”);
}Else if (unlocked == false){
trace(“door is locked”);
}