Chapter 2. Introducing the Basic Syntax of ActionScript

Understanding Object-Oriented Programming

Flash ActionScript programming is built on objects, classes, properties, and methods. Understanding how each building block works can help you understand how to add scripts and produce interactivity in your movies.

Understanding Objects and Classes

Object-oriented programming, or OOP, is a very common programming paradigm, used by most modern languages. In OOP, programmers organize code into objects that mimic real-world concepts, such as shopping carts, or encapsulate specific business models, such as a process to add a new customer to a database. As ActionScript 3.0 is an object-oriented programming language, understanding the basic terminology and concepts of OOP are vital to your success in using it.

As OOP is designed to mimic real-world situations, it can be helpful to think of a real-world analogy to apply to the terms. The following examples compare OOP concepts to the design and construction of a new housing community:

The main building block in OOP is a class. A class defines an object but does not represent an actual instance of the object. Before you can start using objects, you have to create them as a class. In the housing analogy, a new community cannot be built out of thin air. Before any construction can begin, the developers must plan out, or in a sense, define, each model of house they plan to build. To do this, they have a set of blueprints drawn up, one for each house model. These blueprints can be thought of as classes. You cannot actually live in a blueprint, just as you cannot actually use a class in a program; rather, each provides the definition for the actual objects.

Objects are instances of classes. Just as you must build a house based on a blueprint before you can live in it, you must also work with an instance of a class in order to use it. When you create an instance of a class, you are creating an object, an actual "thing" that you can use in the program. When you create an instance of a class in OOP, you instantiate it.

If you have ever placed an instance of a movie clip or a button on the Stage in Flash, you have used objects. In fact, when you convert artwork in Flash to a symbol, you are actually creating a class; when you drag the symbol to the Stage, you are creating an instance of that class — an object.

The Button class in Flash is unique in that instances of it can be created only visually on the Stage. MovieClips, dynamic TextFields, and components are examples of classes that you can instantiate either visually on the Stage or through code. The remaining classes, of which there are several dozen, can be instantiated only through code.

In addition to the predefined classes, you can create your own. As mentioned earlier, you are actually creating a new class every time you create a new symbol. Specific business-logic needs or processes, such as a shopping cart in an e-commerce application, also need to be defined as custom classes. Creating custom classes is beyond the scope of this chapter but is an important topic for further exploration once you understand the basics of ActionScript.

Classes in ActionScript are organized into packages. Each class is defined in its own ActionScript file, and a package is nothing more than a folder that contains a group of related classes.

Understanding Properties and Methods

A real-world object has properties — the things that make up the object. For example, a house can be defined by its square footage, the number of bedrooms and bathrooms it contains, the direction it faces, its color, and many other attributes. In OOP, these attributes are known as properties. Properties can be seen as the "nouns" of an object. Just as you would describe your house by these types of properties listed, you can describe a MovieClip by its shape, its color, its transparency or alpha, and its location on the Stage.

If you live in a modern housing subdivision, you are aware that your community contains only three or four models of houses. These were created from the sets of blueprints commissioned by the developer. Each instance of a particular model of home shares a group of common properties, such as the square footage and number of rooms. However, each house is also unique from the others in the neighborhood. Although you may live in the same model of home as your neighbor, your house is most likely a different color or may be located on a different side of the street. Certainly, your house has a unique address.

Instances of objects in ActionScript also share many properties while having other unique properties. You can create as many instances of a particular MovieClip as you like on the Stage. Each instance shares the same basic shape as each other instance. However, you can position each instance in a different place on the Stage, so their x and y properties are different. You can scale each instance in order to set different scaleX and scaleY properties.

In addition to defining objects through properties, you also want to do things to properties. In your home, you can enter and exit, cook dinner, sleep, watch TV, and work on the computer. Similarly, you need to be able to add and remove products from a shoppingCart class that you define for your e-commerce application. MovieClips can be animated on the Stage. The actions that you can perform to objects are known as methods. Just as properties can be seen as the "nouns" of an object, methods can be seen as the "verbs" of an object.

Most of the time, all instances of an object use a common set of methods. Although it is possible to define custom methods for individual instances of an object, doing so is beyond the scope of this book.

Static Classes

Before continuing, it is important to understand a special type of class in ActionScript. These classes, known as static classes, cannot be instantiated. Instead, you can simply access their properties and methods directly. Static classes are used for cases in which having individual instances does not make logical sense. One example of a static class is Math. The Math class contains a set of properties that define mathematical constants, such as pi, and a set of methods to perform mathematical calculations, such as sine. Although it makes sense that you can have more than one instance of a MovieClip on the Stage and thus need instantiation to control each one separately, it also makes no sense to need to instantiate the Math class: Pi is always pi, and so you do not need a separate instance. Other examples of static classes include Stage, as you cannot have more than one Stage in a movie; Mouse, because you cannot use more than one pointer device at a time on most computers; and Keyboard, as the same applies to keyboards.

Understanding ActionScript Syntax Rules

Like spoken languages, ActionScript has rules of punctuation and grammar that you must follow, and these rules compose the syntax of the scripting language.

Using Semicolons

Each ActionScript statement ends in a semicolon. A statement is generally a single line of code. For example, a statement that declares a variable may look like this:

var myVar:String = "Hello World";

Although the details of declaring variables are discussed in the following section, "Create a Variable," you should note that the line is a single statement and thus ends in a semicolon.

Using Curly Braces and Parentheses

Sometimes, ActionScript code is too complex to be expressed in a single statement. In these cases, you create a code block. A code block begins with a line that defines the block and then the code that will execute. The executable code is enclosed within curly braces. For example, a function declaration is written as a code block:

function myFunction():void
{
     return true;
}

You should always be careful that you close any curly brace you open. Unbalanced braces cause the script to return an error, but the error message often gives you the wrong line number. It is a good habit to always add both the opening and closing curly braces at the same time and then go back and add the code between them.

The same rules apply to the use of parentheses: You must always be sure to close any parentheses that you open. Parentheses are used to call functions and group mathematical operations.

Whitespace

ActionScript is, for the most part, whitespace-insensitive, which simply means that it does not usually matter whether or not you have spaces in your code. As an example, the function declaration to the right could be written with the opening curly brace at the end of the first line or on a separate line as shown. Many developers prefer to put it on the first line, whereas many others prefer to have it on its own line — the choice is yours. The code also executes properly if you do not indent the line of code within the curly braces; however, ensuring that your code is readable saves untold amounts of time when debugging, so it is always recommended that you use whitespace to make your code easy to read. One important exception to this rule is that variable and function names cannot contain spaces.

Case Sensitivity

ActionScript is case-sensitive. If you declare a variable with all lowercase letters, you must always use all lowercase letters to refer to that variable.

Functions, variables, keywords, properties, and methods built into ActionScript are always expressed with camel casing, whereby multiword names begin with a lowercase letter and then use an uppercase letter for the first letter of each additional word. As an example, the property that allows you to scale an object is scaleX — note that the X is uppercase. Classes in ActionScript are all defined using Pascal casing, which follows the same concept as camel casing except that the first letter is also capitalized, such as MovieClip. So that the code you write matches the code built into the language, you should follow this same technique in your code: Use Pascal casing for custom classes you define and camel casing for everything else. You can choose to rely on a different scheme if you prefer; the only truly important factor is that you remain consistent throughout your code.

Dot Syntax

ActionScript uses dot syntax to separate an object name from a property, function, or method. For example, you would set the scaleX property for an instance called myButton by writing myButton.scaleX. The specifics of this concept are explained in later chapters.

Create a Variable

Variables allow you to store information to use later in your script. For example, you can store a customer's name as a variable or the score a player has earned in a game.

In ActionScript, variables are declared using the var keyword, followed by the variable name. The name should be descriptive for easy reference. The variable name must begin with a letter and can contain only letters, numbers, and underscores. The variable name is case-sensitive throughout your script, so you should be consistent in what case you use. Most ActionScript developers rely on a camel casing for their variables, as described in the preceding section. It is not required that you use camel case, but as it is the casing used for built-in variables in the language, using it will ensure that your variable names and those used by the program are consistent and thus easier to remember.

You should always declare a data type for the variable you are creating. You declare the data type by setting it after a colon, which follows the variable name. If the variable contains words or phrases or other alphanumeric characters, you should set the data type to String. If the data is numeric, you typically use the Number data type. A more thorough discussion of data types in ActionScript is in the following section, "Understanding Data Types."

You can give a variable a value when you create it by typing an equal sign and the value. String values must be quoted; numeric values must not be quoted.

Create a Variable

  • Create a Variable
  • Create a Variable

    Note

    See Chapter 1 for details on creating new files and opening the Actions panel.

    Create a Variable
  • Create a Variable
  • Create a Variable

    A list of data types appears.

  • Create a Variable

    Note

    You can also press Enter (Return) when the code hints select the type that you want.

  • Create a Variable
  • Create a Variable
  • Create a Variable

    The variable is created.

Understanding Data Types

ActionScript 3.0 is what is known as a "strongly typed" language, which is simply a way of saying that it understands and recognizes data types and that it forces you to declare these types and use them consistently through your application.

Types of Data

Programming languages, databases, and other computer programs typically need to be able to distinguish pieces of information based on what kind of data they contain. If the type of data is not declared or understood, computers will often make mistakes. For example, in Microsoft Windows, if you have a series of files that begin with numeric characters, they will often be sorted incorrectly, with a file named 1.gif being followed by 10.gif, rather than 2.gif. This is because Windows treats all files types as being made up of strings of characters rather than containing numbers. In this method, each letter is alphabetized individually, so therefore, it makes sense that all files that begin with a 1 come before any files that begin with a 2.

Issues such as these can be solved through data types. If we have the ability to specifically inform the program that a particular piece of data will always contain purely numeric characters, then it will treat them numerically and can correctly sort them, as well as perform math on the data and other functions.

Data Types in ActionScript 3.0

Data types in ActionScript 3.0 are roughly grouped into three categories: fundamental, simple, and complex.

Fundamental Data Types

ActionScript 3.0 defines three basic or fundamental data types: Null, void, and Object. The Null type can have only a single value — null — and means that a particular variable has no value. Note that having no value or being null is not the same as a zero or an empty string, as both of them actually contain some value.

Like Null, void has only a single possible value: undefined. You will most often encounter this type when working with functions that do not return a value, a topic that is discussed in detail in Chapter 5.

The Object type includes all instances of every class but is most often used as a generic type. You will see many instances of relying on the generic Object type as you work through this book.

In addition to these types, ActionScript 3.0 recognizes every class — both those defined in ActionScript 3.0 and those that you define yourself — as a data type. Therefore, as shown later in the subsection "Declaring Data Types," you can set a variable to be of type String, which is in essence creating the variable as an instance of the String class.

Simple Data Types

A single variable can utilize a simple data type. The simple types in ActionScript 3.0 are String, Boolean, Number, int, and uint. Strings are units of characters, such as words or sentences. Strings can contain any type of character, including letters, numbers, and whitespace characters.

The Boolean data type is named for early physicist George Boole and represents true and false values. As with other programming languages, ActionScript 3.0 defines true with the literal word true, as well as any nonzero number, any nonempty string, and any nonnull value.

The Number data type can be used for any purely numeric data. The type contains a set of subtypes to better define the number. For example, you can use the int type for numbers that will contain only integers or whole numbers, whereas uint is for unsigned or positive numbers.

Complex Data Types

Sometimes, you will need variables that store more than one piece of distinct data. This can be done through a complex data type. One common example of a complex data type is an Array, which is covered in later sections of this chapter.

Declaring Data Types

You declare data types in ActionScript 3.0 when you declare variables by typing a colon after the variable name and then the data type. Most, but not all, data types in ActionScript 3.0 are actually classes and will thus begin with a capital letter. For example, say that you wanted to create a variable called firstName and declare that it be data typed as a String. To accomplish this, you would write

var firstName:String;

Untyped Values

In certain situations, you may need to define a value that can be of any data type. It is possible to simply leave off the data type in this case:

var myData;

However, when you or other developers look back over your code, it may not be possible to tell if this variable was left untyped intentionally or if it was simply done in error. Therefore, whenever you use an untyped variable intentionally, you should denote this with an asterisk, as in

var myData:*;

Both examples above function in precisely the same way. Note that this should be done only when absolutely necessary. Variables that are given specific data types can contain only data that is appropriate to that type, and many coding errors can be handled easily due to the debugging messages that will be returned if you, for instance, attempt to put a number into a String variable. Untyped variables will not generate these errors and will often lead to problems that are much more difficult to troubleshoot.

Casting Values

It is possible to convert a variable that had been previously declared as one type to another through a process called casting. To cast a variable to a new type, you write the new type and then include the variable in parentheses after the type:

var member:String = "Mal";
Boolean(member);

In this example, a variable called member is defined as a String and given the value "Mal". Then, the variable is cast as a Boolean type.

Note that casting will not always succeed. In the above example, the code will execute correctly, resulting in member having a value of true because any nonempty string is considered true when cast as a Boolean. However, this code cannot as easily be cast as a Number:

var member:String = "Mal";
Number(member);

In this case, member would now contain the value NaN, or Not a Number, as nonempty, nonnumeric strings cannot be cast to a Number. Note that the reverse will always succeed because Strings can always contain numbers:

var score:Number = 1500;
String(score);

Test Your Flash Movie

In order to effectively test your ActionScript, you will need to test your movie in Flash Player. You can do this at any point by following the steps here.

If you are an experienced Flash designer, you may be familiar with simply pressing the Enter key to test animations directly in the Flash-authoring environment. Although this does indeed work for basic animation, many elements of your movie will not be shown, such as animation that may be contained within MovieClips. Further, it will not preview ActionScript, which can be previewed only directly within Flash Player.

If your ActionScript code contains errors, the Compiler Errors panel will appear and display an error message that specifies on which line the error exists, a description of the error, and the offending code. You can then close the player, fix the error, and test the page again. If multiple errors appear when you test the movie, you should fix them one at a time, testing after each error is fixed, as often a single mistake in the code can result in multiple error messages. If your movie contains trace actions, they will appear in the Output panel. Trace actions are discussed later in this chapter in the section "Trace Variables."

When adding ActionScript to your project, you will most often have the ActionScript panel open. You can test your movie at any time, including when the panel is open. You can also test your movie without needing to save it.

Test Your Flash Movie

  • Test Your Flash Movie
  • Test Your Flash Movie

    You can also press Ctrl + Enter or

    Test Your Flash Movie

    Flash Player opens and plays the movie.

    Note

    In this example, nothing has been added to the movie, so nothing is displayed when the movie plays.

Test Your Flash Movie

Concatenate Strings

One of the most common data types for simple variables is String, which is used to store pieces of text. Depending on how you plan to use the text, you may need to combine multiple strings together into new variables. The process of combining strings is known as concatenation.

ActionScript uses the plus symbol (+) to concatenate strings. For example, if you declare a string variable for a user's first name and another for his last name, you could combine them into a single variable to use his full name:

var fullName:String = firstName + lastName;

Note, however, that if the user's first name is Mal and his last name Reynolds, the preceding code would result in a full name of MalReynolds — without the space. Quite often, you will need to add literal characters, such as spaces, to the string when you concatenate, which you can do by including them in quotation marks:

var fullName:String = firstName + " " + lastName;

Both of the preceding examples show concatenation in a variable declaration. You can concatenate any time you use strings, including when the string is used as an argument in a function or being set as a property of an object.

Concatenate Strings

  • Concatenate Strings
  • Concatenate Strings
  • Concatenate Strings
  • Concatenate Strings
  • Concatenate Strings

    The concatenated variable is created.

Concatenate Strings

Trace Variables

Unfortunately, not all of your code will work correctly the first time that you write it. Typographical errors such as mistyping a variable name or forgetting a semicolon at the end of a line are all too common in coding, but fortunately, Flash Player will generate error dialog boxes when these occur.

Much more difficult to debug are what are known as logical errors. A logical error is when your code is syntactically correct but contains a mistake in the script that causes it to run incorrectly. For example, you may think that a variable is set to one value when in fact it is set to another. When you try to test for the value you believe exists, you get an unexpected result.

Fortunately, ActionScript contains a trace command that enables you to test the values of any variables you need. When you trace a variable, its value appears in the Output panel when you play the movie in Flash Player. You can trace variables, literal values, and other data to test to be sure that their values are what you expect.

trace is a global function. It is available throughout your code, so you can use it at any time. Always write trace in lowercase letters. Always place the value you will be tracing within a set of parentheses. If you are tracing a string, it must be in double quotes; if tracing the value of a variable or object or the value of a number, you will not use quotes.

Trace Variables

Note

You need to open the Actions panel to complete the following steps. See Chapter 1 for more details.

  • Trace Variables
  • Trace Variables

    Note

    See the section "Create a Variable" for information on creating variables.

  • Trace Variables
  • Trace Variables
  • Trace Variables
  • Trace Variables
    Trace Variables
  • Trace Variables
  • Trace Variables

    The movie opens in Flash Player.

  • Trace Variables
Trace Variables

Extra

Although tracing is an important debugging tool, you would not want a final movie to contain the trace statements, as they would confuse your user. You will most likely simply delete the trace statements after you have debugged your code or comment them out, but you can also tell Flash not to export trace commands when you publish the movie. If you click File

Extra

Although you will almost always trace the value of a variable, you can have the trace command display a literal value by placing the value in quotes inside the command's parentheses:

trace("This will be displayed");

Create an Array

ActionScript contains two built-in data types that allow you to store multiple values in a single variable. The simpler of the two is an Array. The more complex option, a generic Object, is discussed later in this chapter in the section "Create a Generic Object."

An array is simply a variable that can hold more than one piece of information. There are several different ways to create arrays. The most formal is to call the Array constructor:

var crewMembers:Array = new Array();

Array stores its values in indexes, which count from zero. You can populate the array, or add values to it, by repeatedly calling the array and the next index number, which is referenced in square brackets:

crewMembers[0] = "Mal";
crewMembers[1] = "Zoe";

A single array can contain values of different data types. Therefore, a single array could contain strings, numbers, other arrays, or other object types.

Create an Array

  • Create an Array
  • Create an Array
  • Create an Array
  • Create an Array
    Create an Array
  • Create an Array
  • Create an Array
    Create an Array
  • Create an Array
  • Create an Array
  • Create an Array
  • Create an Array
  • Repeat steps 7 to 10 to add additional items to the array.

    Create an Array

Apply It

A more efficient method of creating arrays is to include the values that you want to add to your array within the parentheses on the constructor line:

var crewMembers:Array = new Array("Mal", "Zoe", "Wash", "Jayne", "Kaylee", "Simon", "River", "Book", "Inara");

You can shorten this even further by leaving off the new Array and placing the values within square brackets:

var crewMembers:Array = ["Mal", "Zoe", "Wash", "Jayne", "Kaylee", "Simon", "River", "Book", "Inara"];

Each of these methods creates the same array, so the one you choose is ultimately personal preference.

Add and Remove Elements from an Array

The items in an array are technically referred to as elements. After you have initially populated the array, you can add new elements to it or remove existing elements.

You can add a new element to an array by calling one of two methods of the array: push() and unshift(). The push() method adds an element to the end of the array, whereas unshift() adds it to the beginning. For example, if you had an array that contained the values "Serenity", "Star Wars", and "Requiem for a Dream", you could add a new element, "Juno", to it via push():

movieArray.push("Juno");

In this example, "Juno" would become the last element; if you added it via unshift(), it would be the first element. Note that although the placement of the new element varies, the code for adding it is essentially the same:

movieArray.unshift("Juno");

The matching methods to remove elements from an array are pop() and shift(). Whereas push() adds an element to the end of an array, pop() removes the last element; while unshift() adds a new element to the beginning, shift() removes it. Using the same example, calling pop() on the original array would remove "Juno", leaving "Serenity", "Star Wars", and "Requiem for a Dream", while shift() would remove "Serenity" and leave the other three.

Add and Remove Elements from an Array

Add An Element to an Array

  • Add An Element to an Array

    Note

    See the preceding section for details on creating an array.

    Add An Element to an Array
  • Add An Element to an Array
  • Add An Element to an Array

    Note

    If the value being added is a string, be sure to enclose it in quotes.

  • Add An Element to an Array
  • Add An Element to an Array

    Flash Player runs the movie. The Output panel appears and displays the array.

  • Add An Element to an Array

Remove an Element From an Array

  • Remove an Element From an Array
  • Remove an Element From an Array
  • Remove an Element From an Array

    Flash Player runs the movie. The Output panel appears and displays the array.

  • Remove an Element From an Array
Remove an Element From an Array

Extra

If you think that keeping the four methods straight may be difficult, do not worry: You are not alone. In particular, many developers find it difficult to remember whether shift() or unshift() adds or removes an element. Generally, however, you will need to add items to an array much more often than you need to remove them, and as the exact order of the elements in an array rarely matters, you will more likely use push() than any of the other methods.

Most often, when you do remove elements from an array, you will be doing so to put the element into a variable. You can do this by simply assigning the pop() method call to a variable with the correct data type:

var individualMember:String = crewMembers.pop();

You can remove all the elements from an array, one at a time, by looping over the array and calling pop() repeatedly. Looping over arrays is discussed in Chapter 12.

Create an Array in an Array

Sometimes, a more complicated data structure is necessary than can be achieved in either a simple variable or an array. If you need to relate multiple groups of data, you can store arrays within arrays. An array that contains one or more other arrays is known as a multidimensional array.

Although ActionScript arrays can technically contain many dimensions, you will rarely need one with more than two. A two-dimensional array can be seen sort of as a spreadsheet, where the outer array represents the columns and the inner array the rows. For example, if you had an array that represented player ID numbers in a game, you could store an array within each element of that array that contained each player's score.

Arrays within arrays are constructed by creating the first, outer array and then creating a new array within each element of that array:

var players:Array = new Array();
players[0] = new Array();
players[0][0] = 4324;

Create an Array in an Array

  • Create an Array in an Array

    Note

    See the section "Create an Array" for details.

    Create an Array in an Array
  • Create an Array in an Array
  • Create an Array in an Array
    Create an Array in an Array
  • Create an Array in an Array

    The array within an array is created.

Apply It

You can reference elements of the inner array by referencing the index number of each of the arrays. Therefore, given the following array:

var players:Array = new Array();
players[0] = new Array();
players[0][0] = 4324;
players[0][1] = 5545;
players[1][0] = 2234;
players[1][1] = 7685;

You could trace the first player's second score by typing:

trace(players[0][1]);

Create a Generic Object

Many times, complex data can be expressed as either an array or an array of arrays. However, although an array enables you to store multiple pieces of data, you cannot create a logical association between the index — the number used to represent the element of the array — and the value. Depending on the nature of the data you are trying to store, this may be fine, but it may cause problems as well.

For example, say that you had a game and needed to keep track of the player name, her score, and her current level within the game. You could store this as an array, but you would need to remember that you placed the player name as element 0, her score as element 1, and her level as element 2. In this simple example, that would not be difficult, but imagine if you had many dozens of data points. It would quickly become difficult to remember which element contained which piece of data.

In those instances when you need to maintain a relationship between the values in a data store and the indices by which you refer to them, you can use a generic Object. Like an array, generic objects allow you to store multiple values in a single object. But unlike arrays, a generic object is going to contain specific names, called properties, to associate with the values.

You create generic objects in much the same way as you create arrays. The only difference is that with an object, you create the property/value pairs for the data using dot notation, with the object name followed by the property name, an equals sign, and the value.

Create a Generic Object

  • Create a Generic Object
  • Create a Generic Object
  • Create a Generic Object
    Create a Generic Object
  • Create a Generic Object
    Create a Generic Object
  • Create a Generic Object
  • Create a Generic Object
  • Create a Generic Object

    The generic object is created.

Apply It

Both arrays and objects can contain data with varying data types. In an array, this is legal, where we are storing both strings and numbers:

var rawData:Array = new Array("Serenity", 2005, 150000000, "Great movie");

For objects, the same is allowed:

var rawData:Object = new Object();
rawData.movieName = "Serenity";
rawData.releaseYear = 2005;
rawData.gross = 150000000;
rawData.review = "Great movie";

Add Constants

Variables, by definition, contain code that will possibly change over the course of the execution of a movie. In a quiz application, for instance, you will need to constantly update the user's score based on how he or she does in the quiz. However, you may encounter situations in which you want to create a constant: a named reference to something whose value cannot change as the movie runs.

You can create a constant by using the const keyword. The standard practice among ActionScript developers is to use all capital letters for the name of the constant, to more easily distinguish it from a variable. In fact, the language already contains a series of constants, all of which are written this way.

After you assign a value to a constant, you cannot assign another value to it later in your code; doing so will result in an error. Constants are often used to represent static values or settings within a movie. They are particularly useful when a numeric value is required but would be more difficult to remember than a string value. Using the preceding quiz example, you may have a predetermined, set value for the passing grade, but remembering that passing is, say, 73%, could be difficult, so you could instead assign a constant of PASSING_SCORE:

const PASSING_SCORE = 73;

Although the same could be accomplished with a variable, a constant is safer as you cannot inadvertently have a line of code that alters the value later in your script.

Add Constants

  • Add Constants
  • Add Constants
  • Add Constants
  • Add Constants
  • Add Constants
  • Add Constants

    The movie plays in Flash Player.

    Add Constants
  • Add Constants

Add Comments to Your Code

Comments are notes you place in your code that are ignored by Flash Player when the movie runs. You can use comments to document your code.

You should get in the habit of adding comments liberally throughout your code. Many developers add a comment block at the top of their script that states the purpose of the document, who wrote it, and a history of its revisions. You should add a comment above any code block whose functionality might not be clear from reading the code itself. You can also help keep track of closing curly braces on complex code blocks such as functions and conditional statements by adding a comment to the closing brace denoting what exactly it closes.

You can add a comment in a single line by beginning the comment with two slashes. Any text after the slashes is ignored:

var adminStatus:Boolean = true; //used to show extra functionality to admins

You can have a comment span multiple lines by beginning the comment with a slash and an asterisk and ending it with an asterisk and a slash; the text between the sets of symbols is ignored:

/* Code created on 12/4/08.
Revised 1/15/09 */

Add Comments to Your Code

Insert a Single-line comment

  • Insert a Single-line comment
  • Insert a Single-line comment
  • Insert a Single-line comment

    The comment is added to the line.

Insert a Single-line comment

Insert a Multiline comment

  • Insert a Multiline comment
  • Insert a Multiline comment

    Note

    You can have the comment span more than one line.

  • Insert a Multiline comment

    The comment is added to the script.

Understanding Coding Best Practices

Although poorly written, disorganized, or sloppy code will often work and "get the job done," following some accepted coding best practices will enable you to work more quickly, make future edits of your code easier, simplify debugging, and enable others to collaborate on your projects.

Plan and Organize Your Code

Extra time you spend planning your code before you begin typing anything will pay dividends later. Think about what your code needs to accomplish and what the best ways might be to achieve that goal.

Keep your code organized. Group all variable declarations at the top of your code so that they are easy to find for reference later. Group other similar code blocks, such as functions or event handlers, together to make them easy to locate when you need to edit them later. If you are setting a series of properties on an object, place all the code to do so together in a single block. The more organized you keep your code, the easier it will be to maintain.

Be Consistent

As mentioned earlier, ActionScript is case-sensitive. You can use any casing scheme that you want for variables, but as you must always type a variable using the same case as you did when you declared it, always being consistent in your casing will make it easier to be sure that you are typing variable names correctly.

The same consistency should apply in the names you use. Do not, for instance, have a variable to capture the first name of a user called fname while having another variable for the last name called lastname. Either is legal and will work, but the point is that they should either both use a single initial for the first word or both spell it out. You can use underscores in names as well, so first_name is also legal, but again, it should only be used if other variables will follow the same pattern and be last_name and street_address.

Immediately Add Closing Parentheses and Curly Braces

Code blocks such as functions, discussed in Chapter 5, and conditional statements, discussed in Chapter 11, require the use of curly braces to denote their code. When you write these statements, get in the habit of adding the closing curly brace at the same time as you add the opening one. In other words, type the skeleton of the function first:

function sampleFunction(){
}

Then go back and add the necessary code between the braces. Doing this will ensure that you do not forget to add the closing brace after entering the code for the function.

The same should apply when you add parentheses. Parentheses are used when creating and calling functions and when writing complex mathematical operations. Often, you will have nested sets of parentheses, so it is easy to lose track of how many closing parentheses you need at the end of an expression. If you add each closing parenthesis as you add its opening partner, you will not have to worry about not having the correct number of closing parentheses at the end.

Add Whitespace

ActionScript is whitespace insensitive, so you can improve the readability of your code by adding whitespace. Take for example this block of code, which takes two strings and concatenates them together but uses a minimal amount of whitespace:

var firstName:String = "Inara";
var lastName:String = "Serra";
function concatNames(str1:String,
  str2:String):String{return firstName + " "
  lastName;}

Compare the preceding to this code, which is spaced out better:

var firstName:String = "Inara";
var lastName:String = "Serra";
function concatNames(str1:String,
str2:String):String{
         return firstName + " " lastName;
}

The results of running each block will be the same, but editing or debugging the second block would be much easier because the whitespace makes it more readable.

Document the Code with Comments

Liberally commenting your code will help explain the purpose of code blocks to yourself and other developers who may need to edit the script in the future. Any block or line of code that is not immediately clear from reading it should have explanatory comments.

Use Descriptive Names

Always use descriptive names in your code. Avoid vague, generic, or potentially confusing names. For example, store numbers in variables named numberToAdd or playerScore rather than x or y. Descriptive names are easier to remember and make your code clearer in general: You can tell or at least guess at the purpose of a variable numberToAdd or firstName, whereas a variable x could represent just about anything.

Functions should be named following the verbNoun convention and be given names that describe their purpose. In other words, if you have a function that will add a series of numbers, calling it addNumbers follows the verbNoun convention and makes the function's purpose clear at a glance.

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

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