Introduction to ActionScript 3.0/Printable version

From Wikibooks, open books for an open world
Jump to navigation Jump to search


Introduction to ActionScript 3.0

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Introduction_to_ActionScript_3.0

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

Introduction

Introduction to ActionScript 3.0
Printable version Class structure

ActionScript is the programming language used in Flash projects. This book is intended to help anyone, including those without programming experience, to learn ActionScript and programming in general.

Note that if you have programming experience, this book will be quite easy for you. Just learn the juicy syntax and standard library!


What this book does not aim to do[edit | edit source]

  • This book is not about the production of Flash games or websites. The information presented in this book should be helpful for all novice Flash programmers, not just those who would like to create a game or interactive website.
  • To learn more, get a more advanced book or check out the official ActionScript documentation.

Why learn AS3 instead of AS2?[edit | edit source]

Back in the AS2 days, it was often said that ActionScript's simplicity allows non-programmers to program. With AS3, the language has become a whole lot more complicated. However, AS3 has introduced many features that allows you to gain more wholesome programming experience, better-structured code, and in general produce faster and more powerful applications. These features include:

  • Improved event handling. In AS2, event handlers were simply properties of objects. You didn't have to worry about event dispatching or event bubbling (and instead addressed parents). Very often, you didn't even have to worry about attaching event listeners. Not anymore. Now you have full control over the entire event-handling business!
  • Improved standard library. In AS2, nested MovieClips were the centre of the universe. attachMovie and createEmptyMovieClip were used to attach MovieClips in other MovieClips. Although convenient, this led to numerous problems with code structured and the like.
  • Mandatory data typing. In AS2, data typing was optional. This is not longer the case in AS3.

There are many more advantages, but we won't go into everything one by one. Let's just begin our adventures in AS3!

How is this book organised?[edit | edit source]

Good question! This book is organised into four sections, each with its own objective.

Section I: The Bare Basics of ActionScript[edit | edit source]

In the first section, we will explore the ActionScript language. If ActionScript were a human language, this section will teach you the basic grammar, function words and sentence structures of that language. We will explore ActionScript as an object-oriented language, create classes and so on.

Section II: The Building Blocks of an ActionScript application[edit | edit source]

Knowing the grammar and sentence structure of a language is not enough! We need to learn vocabulary: words and phrases that enrich our application. In this chapter, we will learn how to build an application with resources including graphics, sounds and text. We will also look at timing and Mathematics, etc.

Section III: ActionScript and the Outside World[edit | edit source]

Having created an awesome Flash application is great, but Flash should not be an isolated object. It should also interact with the user's computer, with other servers, with other languages, and so on. This section is all about Flash communicating with the outside world.

Section IV: Going Advanced[edit | edit source]

In this section, we will go into greater detail the things we've learnt in previous sections. We'll also learn how best to design our applications.


Class structure

Introduction to ActionScript 3.0
Introduction Printable version Variables and Data Type


Key concepts:


  • Objects, methods and properties
  • Classes
  • Packages
  • Importing
  • Variables and constants
  • Integrated development environments
  • Compilation
  • Document class
  • Object instantiation

Definition: Organization of classes in a society

Ah, classes. ActionScript projects are essentially made up of classes. (OK, there are interfaces too, but we'll cover them later.)

What is object-oriented programming?[edit | edit source]

Object-oriented programming, as the name suggests, is a programming paradigm that involves the creation of and interaction among objects. An object consists of two parts:

  • Properties that define the object's characteristics. For example, an apple may have properties like 'size', 'colour', 'juiciness', and so on.
  • Methods that define what the object can do. Methods are a subset of functions, which we'll discuss later. An apple may have methods like 'transport', 'eat', etc.

What are classes made of?[edit | edit source]

A class in ActionScript 3.0 looks like this. Let's look at it the elements of it, one by one.

package {
	import flash.display.Sprite;
	import flash.events.Event;
	
	/**
	 * @author WikibooksOverlord
	 */	

	public class Main extends Sprite{

		private const HELLO_WORLD:String = "Hello, world!";
		private var _username:String = "Daniel";
		
		public function Main():void{
			if (stage) init(null);
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			//You can start changing from this line.
			trace(HELLO_WORLD); //This line outputs 'Hello, world!' for now.
			trace("Your name is " + name + ".");
			//Don't touch anything below this line.
		}
		
	}
	
}

Package definitions[edit | edit source]

package {

A package is a group of classes and other stuff inside a certain directory. The line of code above is called a package definition. For example, a package called 'fruit' might contain classes like Fruit and Apple.

The word 'package' here is a keyword. A keyword is a word used by the language for basic operations.

In our case, our class is stored in the main package, so we don't need additional information after the 'package' keyword. To specify that our class resides in the 'food' package, we can append the package name after the 'package' keyword:

package food{

If there's a 'fruit' package inside the 'food' package, we separate the larger package and the smaller package with a dot ('.'):

package food.fruit{

Apart from improving organisation, classes inside a package may have the same name as classes inside other packages. The package name is what distinguishes between them. You can have a class called applicances.Iron and another called materials.Iron.

Notice that the opening brace after the definition is matched by a closing brace at the end of the class file. Everything else in the program is set to be enclosed in this block. A block is a logical 'unit' of commands, or directives, enclosed by a pair of braces. By convention, everything inside a block should be indented, as shown above. Indentation improves code readability a lot, but it is not necessary for the program to work. (In fact, you could put everything in a class into one line and it would still work; however, the code will no longer be readable.)

Also notice that all package names start with lowercase letters, while all class names start with uppercase letters. This is a universally accepted convention that should be followed, even though the code still works if you rebel.

Import statements[edit | edit source]

	import flash.display.Sprite;
	import flash.events.Event;

An import statement is needed if we want to use classes from other packages, such as the standard library. In this case, we have imported two packages from the standard library: flash.display.Sprite and flash.events.Event. The standard library is a bunch of code that controls the basic operations of our Flash operation, such as text, graphics, sounds and so on. There are alternatives to the standard library, but that will not be covered here.

Sometimes, if we're lazy, we can import everything in a package with an asterisk (*):

	import flash.events.*;

As you can see, the syntax for an import statement is the 'import' keyword, followed by the path to the package. Note that although flash.display.Sprite and flash.events.Event are predefined classes, they are not keywords as they belong to the standard library rather than the language itself.

Once imported, we can use those classes in any way we want.

Class definitions[edit | edit source]

Class Structure: An organization of class with in a society.

	public class Main extends Sprite{

In this statement, the 'public' keyword tells us that we can use the class anywhere, even if we're outside the current package. This is known as a namespace attribute. Namespaces handle access control; that is, how the class can be accessed (surprisingly enough). There are only two possible namespace attributes for classes:

  • public tells us that we can use the class anywhere.
  • internal tells us that we can use the class in classes of the same package. It is the default attribute, so if you skip the namespace attribute altogether, the namespace will be automatically set to 'internal'.

After the namespace attribute, we find another keyword, 'class'. Then we see the class identifier Main. (An identifier is a 'name' that uniquely identifies something within a namespace. The full name of that something is the namespace plus the identifier. This will be covered later; for now, you can just treat the word 'identifier' as a special 'name'.)

After that, we see the keyword 'extends', followed by the class name 'Sprite'. This indicates that our Main class is a subclass of the Sprite class. Later, when we learn what the Main class actually is and what subclasses are, you'll understand what we're doing in this line. For now, just take it for granted.

Class members[edit | edit source]

Class members include properties and methods. Properties can be constants, which never change, or variables, which change.

	private const HELLO_WORLD:String = "Hello, world!";
	private var _username:String = "Daniel";

'private' is another namespace attribute we use on class members. There are four possible namespace attributes (apart from user-defined ones):

  • public tells us that we can use the member anywhere.
  • internal tells us that we can access the member in classes of the same package. It is the default attribute, so if you skip the namespace attribute altogether, the namespace will be automatically set to 'internal'. Later, we'll learn to access members of other classes.
  • protected tells us that only the class itself and its subclasses can access the member.
  • private is the most restrictive attribute. Only the class itself can access the member. Not even subclasses have permission.

In general, the attributes we choose should be as restrictive as possible.

In the lines of code above, we have defined and initialised a constant and a variable. In the next chapter, we'll cover what these two lines actually do.

Here are our method definitions:

		public function Main():void{
			if (stage) init(null);
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			//You can start changing from this line.
			trace(HELLO_WORLD); //This line outputs 'Hello, world!' for now.
			trace("Your name is " + name + ".");
			//Don't touch anything below this line.
		}

In the above, we can see two method definitions: Main and init. Main is called the constructor of the class. When a class is initialised, this method is called to set things up. Note that constructors are always public. init is a private function that can only be called within the class.

There are a plenty of things in this code snippet that you don't understand. Don't worry - we'll cover everything in the first section. For now, just take it for granted that it works!

Comments[edit | edit source]

A comment does not change how the program work, but is an efficient way to add information to the program, whether for yourself or other programmers. There are two kinds of comments:

The first type of comments starts with // and is added to the end of the line. It cannot extend over one line. This type of comment is usually used to explain code.

			trace(HELLO_WORLD); //This line outputs 'Hello, world!' for now.
			trace("Your name is " + name + ".");
			//Don't touch anything below this line.

The second type of comments, enclosed by /* and */, allows for multiple lines. /* marks the beginning of the comment and */ marks the end of it. This type of comment can also be added in the middle of a line. They are widely used for elements such as to-do lists and copyright information. This is an example:

	/*Lorem ipsum
	The quick brown fox
	Jumped over the lazy dog */

As you may have noticed, this kind of comment did appear in our Main class. However, it looks a bit different. This is because it is a Javadoc comment, which will be covered later.

	/**
	 * @author WikibooksOverlord
	 */

Sometimes, we need to 'hide' some code temporarily. This can be achieved turning code into comments. This technique is known as commenting out.

How does Flash actually work?[edit | edit source]

What are integrated development environments?[edit | edit source]

The .as file we created above was just a text file; it didn't do anything constructive for us. To get the program to work, we need a compiler. Before getting to compilers, let's look at the different integrated development environments (IDEs) for coding in ActionScript. Although you can use a text editor to code in ActionScript and feed it into a command-line compiler, it is not recommended to do so. An integrated development environment typically contains the following features:

  • A project management system that organises the resources and files the project uses.
  • Syntax highlighting is a feature in which different parts of code are coloured to improve code readability. In this book, syntax colouring is achieved with the MediaWiki software.
  • Code hinting speeds up development by reminding you what you need to type next.
  • Syntax checkers which check your syntax.
  • A built-in compiler and debugging utility/debugger which allows you to compile and debug in the IDE. We will cover debuggers later.

A good IDE also provides features for the editing of related markup languages like MXML (which is outside the scope of this book but very helpful for ActionScript interfaces).

Common IDEs for Flash include:

  • Flash Professional: The first Flash authoring software, Flash Professional combines animation and coding into one piece of software. However, its IDE abilities are limited as a result. Flash CS3 and above supports AS3.
  • Eclipse: An all-purpose IDE used for many different languages, including ActionScript.
  • Flash Builder: A proprietory IDE based on Eclipse.
  • FlashDevelop: An open-source IDE geared towards ActionScript. It provides handy features such as SharedObject tracing and also contains advanced code hinting features.

In this book, we will provide instructions for FlashDevelop. If you use other IDEs, refer to the relevant documentation.

What is compilation?[edit | edit source]

Computers only understand machine language. ActionScript is a human-readable language, but not a computer-readable one. The more high-level a language is, the closer it is to the computer system. Machine code and assembly language are the lowest-level languages in that they boss around different parts of the computer system directly. Higher-level languages must be converted into lower-level languages for the computer to understand. A compiler is a program that converts code from a high-level programming language into a low-level language.

For ActionScript, it is a bit more complicated. An ActionScript compiler compiles our ActionScript into a lower-level language known as ActionScript Bytecode (ABC). Then, the ABC is wrapped together with the resouces (music, graphics, and so on) into another file known as a Shockwave Flash file (SWF), a magic performed by a SWF compiler. Flash Professional uses a SWF compiler called the Flash compiler, while FlashDevelop, Flash Builder, etc., use a SWF compiler called the Flex compiler.

The ABC is then executed by a runtime environment called Flash Player using the embedded resources. The runtime environment compiles the ABC into machine language that controls the computer's hardware. This conversion is performed in real time, and is known as just-in-time compilation.

There are two kinds of compilation, debug build and release build. Debug build is what you'll build during the development of your project. Once your project is ready for compilation, you will compile the release build, which is faster and more lightweight. To toggle between the builds, FlashDevelop has a toolbar on top with a drop-down menu that shows the tooltip 'Select Configuration' when you hover over it.

Let's do it![edit | edit source]

Now open the IDE of your choice and create a new project. In FlashDevelop, click on Project > New Project > AS3 Project. Name your project whatever you want. Now add the following folders to your project's main folder if they aren't already there:

  • src contains your project's source code.
  • bin contains your project's compiled binary (i.e. the SWF file if you've read the above section carefully).

Next, in the 'project' screen of your IDE, locate the Main class. If it isn't already there, create one. Copy the code above directly onto the text file. Set it as the document class (in FlashDevelop, right-click on the file in the Projects window and check 'Document class').

Now, set the compiler to compile to \bin\MyFile.swf (Project > Properties > Output in FlashDevelop). Now compile and run the project (CTRL + ENTER or the blue 'play' button in FlashDevelop).

If you've done everything correctly, you should see this in the output screen of your IDE:

Hello, world!
Your name is Daniel.

What happened just now?[edit | edit source]

Once a Flash application is started, the very first thing that happens is:

  1. A new instance of the document class is instantiated.
  2. The new instance is added to the stage.

Now, you may be completely confused. Don't let those new words intimidate you! We'll look at everything one by one.

Object instantiation[edit | edit source]

Let's say we now have a class called Apple. Fortunately, in the programming world, you don't need to take the time to grow the apple. All you need is to create an instance of the Apple class. To create 200 apples, create 200 intsances of the Apple class. The creation of an instance is called instantiation.

Usually, object instantiation is done using the new keyword. For example, the expression new Apple() instantiates a new apple. (Note that the round brackets here can be skipped.) However, our Main class here is a document class. That means the runtime environment very kindly instantiated the Main class for us.


Variables and Data Type

Introduction to ActionScript 3.0
Class structure Printable version Functions

Key concepts:


  • Data types
  • Primitive data types vs. Composite data types
  • Literals
  • Typecasting
  • The concepts of variables and constants
  • Variable declaration, access and value assignment
  • Statements vs. expressions
  • Rules and conventiosn for variable naming
  • Type checking
  • null
  • Use of * in data typing

Before we start doing any programming work, we need to work on our basics. Let's start with data types and variables.


What is a data type?[edit | edit source]

When we work on a Flash project, there are a lot of data and multimedia elements we need to manage: numbers, text, pictures, and so on. A data type is a type of data in our application.

What is a primitive data type?[edit | edit source]

A primitive data type is a type of data that isn't based on any other data types. The primitive data types we're going to use are as follows:

  • Number (e.g. 1, -3254, 123.045)
  • uint (e.g. 1, 3254, 123)
  • int (e.g. 1, -3254, 123)
  • String (e.g. "My name is Joe Bloggs", "ActionScript")
  • Boolean (true or false)

The difference between uint and int is that uint is unsigned, meaning it can't be negative. int is signed, so it can be positive. int takes up more space than uint.[1] Number can represent any floating-point number.

ActionScript's data types are much simpler than most computer languages. There is no 'char' type - String is already a primitive data type, and if we want to store a character, we can put it in a string. There's only one kind of string: none of that CHAR/VARCHAR business in SQL.

Note the double quotes around the strings. One should always enclose a string with double quotes. The double quotes tells Flash that it's a string, not a variable name or anything else. true is a Boolean value, while "true" is a string.

The examples above are all examples of literals. Literals are a way of representing certain values, including primitive data types, XML, regular expressions and objects, in textual form. For example, you can't change the value of 3254, can you?

How can I convert between data types?[edit | edit source]

DataType(Value) is used to convert between data types. This technique is known as typecasting. For example:

  • To convert a number or Boolean to a string, type String(Value). For example, String(3) yields "3", String(false) yields "false", and String(true) yields "true".
  • To convert a Boolean or string to a number, type Number(Value). For example, Number(true) yields 1, Number(false) yields 0, and Number("12") yields 12.
  • To convert a number into a Boolean, type Boolean(Value). Boolean(0) yields false and Boolean(1) yields true.

When converting a value to Boolean, simple keep this in mind:

  • null, undefined, NaN, 0 and empty strings ("") return false. (We'll discuss null, undefined and NaN in a moment.)
  • Everything else returns true.

Care should be taken when converting between the different types of numbers. For example, uint(-1) gives the number 4294967295. This is because of a peculiarity of the two's complement representation system we won't go into here.

There is more to typecasting than meets the eye, though. As we progress through the book, we will look into this technique with more detail.

What is a composite data type?[edit | edit source]

Any data type that is not of a primitive data type is a composite data type. Composite data types are actually classes. The Object class is a prototypical object that has nothing inside it whatsoever. Classes all extend the Object class by default.

What are variables and constants?[edit | edit source]

Every entity, of every type, can be stored in a variable. Consider a variable a 'jar'. This jar can be used to store a lot of things. Most jars are of a special shape that only allows it to store one type of variable (which we'll see below). Sometimes, it stores an actual thing; other times, it stores a link to another thing that is too big to put into a jar. A variable's value may change, which is why it is called a variable.

There are many types of variables, including:

  • Instance properties belong to one instant of an object. For example, an apple may have a 'colour' property. Depending on the apple, its value may be "green" or "red".
  • Static properties belong to the class itself, and not the instants. Once it changes, it changes for all instances of that class. For example, the Apple class may have a 'geneSequence' property.
  • Local variables, or variables within a function.
  • Global variables belong to the package rather than the class.

There are equally many types of constant, including:[2]

  • Instance properties belong to one instant of an object. (They are not used very often.)
  • Static properties belong to the class itself, and not the instants. (We will discuss an example of its use later in this chapter.)
  • Local constants, or constants within a function.
  • Global constants belong to the package rather than the class.

This classification will come in handy when we deal with variable and constant access later.

How can I define and assign values to a variable or constant?[edit | edit source]

How can I define a variable?[edit | edit source]

The syntax for declaring an variable instance property is as follows:

namespaceAttribute var variableName:DataType;

Here's an example:

public var colour:String;

If we want to make it static instead, we simply insert the attribute 'static' after the namespace attribute:

namespaceAttribute static var variableName:DataType;

Another example:

public static var speciesName:String;

Local variables are basically the same story without attributes:

var variableName:DataType;

Obligatory example:

var speciesName:String;


How can I access variables?[edit | edit source]

An expression is, in simple words, how we represent a value in code. Examples of expressions include literals (13.4, "hello world", true, etc.), variable names (myVariable), etc. It is contrasted with a statement, which is a command which actually tells the computer to do something.

To do something to a variable, we must access it. That means we need to write an expression whose value is the variable in question. That sounds really abstract, so let's just learn how to access variables!

How can I access instance properties?[edit | edit source]

To access an instance property, we write this:

myObjectInstance.myProperty

For example, this expression can access the 'colour' property of an apple:

myAppleInstance.colour

Now, let's say we're inside a function of our Apple class, and we want to write an expression that references the current instance. Simple: We use the 'this' keyword:

this

To access a property of the current instance, we have two choices:

this.myProperty
myProperty

Yes, we don't even have to type in the 'this.' if we don't want to! Well, most of the time. Sometimes, we do need to type in 'this.'. We'll touch on this case in the next chapter - be patient. Meanwhile, here's an example within the Apple class:

 this.colour
 colour


How can I access static properties?[edit | edit source]

To access a static property, instead of the name of the instance, you put the class name in front of the dot:

Apple.speciesName

If we're accessing static properties within the same class, we can skip the first part:

speciesName

You cannot have a static property and an instance property with the same name within the same class. Therefore, you don't have to worry about ambiguity just yet.

How can I access local variables?[edit | edit source]

To access a local variable, simply type in the name:

colour

However, local variables and static/instance properties can have the same name, resulting in a naming conflict. In this case, we are no longer allowed to be lazy.

var colour:String;
var speciesName:String;

colour //This expression refers to the local variable 'colour'.
speciesName //This expression refers to the local variable 'speciesName'.
this.colour //This expression refers to the instance variable 'colour'.
Apple.speciesName //This expresion refers to the instance variable 'speciesName'.

A quick note[edit | edit source]

Now let's revisit the example we saw above:

myAppleInstance.colour

Here, myAppleInstance is either a) a local variable or b) a property of the current instance. In the latter case, the above expression 'implies' this expression:

this.myAppleInstance.colour

Apart from using full stops (.) as described above, an alternative way to access a property of a class is to treat the property name as a string:

myObjectInstance["myProperty"]

We'll discuss the uses and demerits of this in a later chapter.

How can I assign a value to a variable?[edit | edit source]

So far, we've only declared variables. They do not contain any content. That is not very useful, which is why we should assign a value to the variable.

The syntax for assigning a value to a variable is very simple:

myVariable = myValue;

You should replace myVariable with one of the variable access expressions we described in the above section. For example:

/*This assigns the string "green" to colour.
'colour' can be any of the following:
- The 'colour' property of the current instance,
- The static 'colour' property of the current class,
- or a local variable named 'green'.
In the first and second cases, this line of code should be located INSIDE the apple class.*/
colour = "green"; 

/*This assigns the string "green" to the 'colour' property of the current instance.*/
this.colour = "green"; 

/*This assigns the string "green" to the 'colour property of the 'myApple' instance.
This line of code should be located OUTSIDE the apple class.
myApple is either a local variable, */
myApple.colour = "green"; 

/*This assigns a newly-initialised Juice object to myApple.
This line of code should also be located OUTSIDE the apple class.*/
myApple.juice = new Juice();

What happens when I assign a variable into another variable?[edit | edit source]

Now for an important concept! There are actually two separate things that may happen when you assign a variable to another variable. It all depends on whether you're dealing with a primitive data type:

var myString:String = "Hi";

/*The computer COPIES the string in myString to "Hi".
myString and myOtherString now refer to two separate data,
located in two separate spots on the computer's memory! */
myOtherString = myString; 

myString = "Bye";
/*At this point, we note that:
-The value of myString is "Bye"
-The value of myOtherString is still "hi"
*/

var myDog:Dog = new Dog();
myDog.species = "golden retriever";

/*The computer passes a REFERENCE to myFirstPet.
myFirstPet and myDog are one entity.
They refer to the same spot on the computer's memory!*/
myFirstPet = myDog; 

myDog.species = "peking";
/*At this point, we note that:
-The value of myDog.species is "peking"
-The value of myFirstPet.species is "peking"
as myDog and myFirstPet are now referring to the same entity.
*/

/*This line of code assigns a new reference to myDog.
myDog and myFirstPet now refer to two separate entities.*/
myDog = new Dog();

myDog.species = "chihuahua";
/*At this point, we note that:
-The value of myDog.species is "chihuahua"
-The value of myFirstPet.species is still "peking"
*/

As the comments above have kindly explained for us, assigning the value of a variable with a primitive data type to another one will copy the datum over. They refer to two different spots in the computer's memory. As you can see above, assigning another variable to myString didn't change myOtherString because they are separate.

On the contrary, assigning the variable containing an object to another variable will only pass a reference to the new variable. They refer to the same spot on the computer's memory. That's why, when we changed the species of myDog, the species of myFirstPet also changed. (A dog can't have two species at the same time, can it?)

However, once we assigned a new instance of Dog into myDog, myDog started referring to a new entity, separate from myFirstPet. Thus changing the species of myDog did not change the species of myFirstPet.

How can I initialise a variable?[edit | edit source]

There's a quicker way to declare a variable and assign a value to it. This is called initialising the variable. If we don't initialise a variable, we'll eventually have to do it anyway.

The syntax for initialising a variable is as follows:

attributes var myVariableName:MyDataType = myInitialValue;

We simple combined the assignment statement and the declaration into one line of code. For variables, this is optional. Recall the variable definition we saw in our Main.as last chapter:

        private var _username:String = "Daniel";

Constants: Basically the same story[edit | edit source]

Constants are very similar to variables, except this time, initialisation is compulsory, and you may not assign any values to the constant afterwards. The exact syntax is as follows:

attributes const myConstantName:MyDataType = myValue;

Looks familiar? It should: we saw one last chapter.

        private const HELLO_WORLD:String = "Hello, world!";

The syntax for accessing constants is exactly the same as that of variables, so we won't repeat everything here. Simply read through the variable access section above, substituting 'variables' for 'constants'.

How should I name my variables and constants?[edit | edit source]

What rules restrict my naming?[edit | edit source]

Like most programming languages, ActionScript does not allow certain names.

  • All variable names must start with a letter, an underscore (_) or a dollar sign($). Numbers are also allowed after the first character. No other characters should be used.
  • Variable names are case-sensitive. That means thisVariable and thisvariable are two distinct variables.
  • Reserved words are keywords that cannot be used as variable or constant identifiers (or function identifiers, as we'll see next chapter). Here's a list of reserved words (we'll learn the uses of all these keywords in this book):
  • as
  • break
  • case
  • catch
  • class
  • const
  • continue
  • default
  • delete
  • do
  • else
  • extends
  • false
  • finally
  • for
  • function
  • if
  • implements
  • import
  • in
  • instanceof
  • interface
  • internal
  • is
  • native
  • new
  • null
  • package
  • private
  • protected
  • public
  • return
  • super
  • switch
  • this
  • throw
  • try
  • typeof
  • use
  • var
  • void
  • while
  • with
  • Some words can, technically, be used as identifiers, but have special meanings in certain contexts. Such syntactic keywords include:
  • each
  • get
  • set
  • namespace
  • include
  • dynamic
  • final
  • native
  • override
  • static
  • Some words are not reserved words at the moment, but they may be used in future releases of Flash, so it's best not to touch them, either, lest your application should go wrong in future versions of Flash Player. (The 'as' and 'const' keywords, for example, used to belong to this category, and are now on the official list of reserved words. Conversely, the 'intrinsic' keyword was moved from the reserved word list to here.)
  • abstract
  • boolean
  • bytes
  • cast
  • char
  • debugger
  • double
  • enum
  • export
  • float
  • goto
  • intrinsic
  • long
  • prototype
  • short
  • synchronized
  • throws
  • to
  • transient
  • type
  • virtual
  • volatile

What naming conventions should I follow?[edit | edit source]

Apart from the rules above, we should also follow naming conventions.

  • Most of the time, variables should always start with a lowercase letter and consist of words smashed together using CamelCase. For example, instead of $Animalspecies, you should name the variable animalSpecies. For private and protected variables, it is common (and sometimes necessary) to add an underscore before the variable name, e.g. _animalSpecies. We'll look at this later.
  • Variable names should be as concise as possible, but should give enough information as to what it is. In general, obscure abbreviations should be avoided.
  • A conventional way to name Boolean variables is to use a verb of the third person at the beginning. The most common type is verb to be + complement, such as isHappy, isPaused, etc. Other examples of good Boolean names include likesCheese, hasPimples, and so on.
  • Constants are named like variables, except everything is in UPPERCASE and SEPARATED_BY_UNDERSCORES.

When is type checking?[edit | edit source]

ActionScript 3.0 is a strongly-typed language. That means variables and constants must have a data type stated. When the program is compiled, the compiler will generate an error if you try to 'fit a square peg in a round hole' by putting an object of one type into a variable that accepts another type. For example, look at this code:

var dog:Dog = new Dog();
var cat:Cat = dog;

This code will generate this error:

Implicit coercion of a value with static type Dog to a possibly unrelated type Cat.

Such is the importance of typecasting: it generates an error to help you fix it. Some languages, such as JavaScipt, are weakly-typed languages. Variables can contain data of any type. Therefore, this code does not result in an error (actually, JavaScript doesn't even have a compiler, but that's another story):

var dog = new Dog();
var cat = dog;

As a result, you may spend hours scratching your head wondering why you application isn't working before you realise what happened. Now, putting a dog into a variable for cats may not be the must common error, but once you get to similar classes - such as XML and XMLList - it is common to get confused. In fact, type errors are the second most common type of programming errors, second only to syntax errors.

What is null?[edit | edit source]

In ActionScript, there are two values that can fit into all variables: null and undefined. We'll look into null for now, and save undefined for later.

null is a special value that can fit into variables of any type. The only exceptions are Boolean, uint, int and Number, which do not accept null (but accept undefined). When a variable other than these four types is first created, it starts out as a 'null' value. In addition, null is commonly used to indicate that something doesn't exist. For example:

if(myDog == null){ //This lines means 'if the value of myDog is null'
     trace("I don't have a dog!");
}

In the above example, we traced 'I don't have a dog!' if myDog is null. (You don't have to understand the code for now, just the concept.)

This does not work for numbers, however. We'll look into this in a future section.

How can I create a variable without datatyping?[edit | edit source]

Occasionally, we want a 'generic' variable that accepts every and any data type. In this case, simply replace the data type with an asterisk (*):

var iHoldAnything:* = new Object;
iHoldAnything = "Hello world!";
iHoldAnything = 12.3;

This technique should be used sparingly to take full advantage of the compiler errors.

How can I determine if an object or datum belongs to a certain type?[edit | edit source]

There are two keywords that help us determine the data type of an object: 'typeof' and 'is'.

How can I use typeof?[edit | edit source]

The syntax for typeof is as follows:

typeof myExpression

This is an expression that may have several possible values, all self-explanatory strings:

  • "number" - this includes Number, uint and int.
  • "string"
  • "boolean"
  • "function"
  • "object" - everything else.

For example:

var myVariable:uint = 12;
var dataTypeOfMyVariable:String = typeof myVariable;
//The value of dataTypeOfMyVariable is "number".

var dataTypeOfDataTypeOfMyVariable:String = typeof dataTypeOfMyVariable ;
//The value of dataTypeOfDataTypeOfMyVariable is "string".

How can I use is?[edit | edit source]

'is' is a bit different from typeof. We use 'is' when we already have a data type in mind, and want to see if our expression belongs to that data type. It returns a Boolean variable.

myExpression is MyDataType
var is12AUint:Boolean = 12 is uint; //true
var isNeg12AUint:Boolean = -12 is uint; //false
var isCurrentObjectASprite = this is Sprite;
//true or false, depending on whether the current object is a sprite

Things will get interesting once we get to subclasses. For now, let's be happy with the current uses of 'is'!

Conclusion[edit | edit source]

Now that you have an idea how variables, constants and data types work, let's move on to the second chapter: Functions.

Note[edit | edit source]

  1. Signed integers need a sign bit in the two's complement representation. This is not required by unsigned integers.
  2. AS3 no longer supports global variables.


Functions

Introduction to ActionScript 3.0
Variables and Data Type Printable version Operators

Key concepts:


  • Definition of functions
  • Function declarations
  • Function calls
  • Parameters
  • Return values
  • Naming functions
  • Callers and callees
  • Functions in variables

Now that we've learnt all our operators, we can get to the next part: functions.

What is a function?[edit | edit source]

In mathematics, a function consists of an input, a process and an output. For example, if x = 3 is input into f(x) = 2x, we get the output 6.

In computers, a function is a collection of statements. When a function is executed, all the statements inside the function will be performed. A function may or may not have inputs, and a function may or may not have outputs. (The latter, of course, cannot be said of spreadsheet functions, which must have outputs.)

There are several kinds of functions:

  • Constructor methods, as we've discussed before, initialise and instantiate an object.
  • Instance methods are methods that belong to the instance of an object.
  • Static methods are methods that belong to the class itself, and not the individual objects.
  • Global functions belong to the package.
  • Top-level functions are special functions that can be accessed anywhere in the program. You cannot create your own top-level functions.
  • In addition, some functions are simply stored in variables.

We'll discuss each type of function in the following text. First, we'll have to learn to construct and 'call' functions.

How can I declare a function?[edit | edit source]

How can I declare and a function with no inputs or outputs?[edit | edit source]

Here's a simple function with no outputs and no inputs. Look at the code and we'll explain it step by step:

private var someNumber:Number = 5;
private function addOneToSomeNumber():void{
    someNumber++;
}

Firstly, the first statement is a simple variable declaration statement we've already learnt before.

The second line has various elements:

  • function is added to the beginning of a function declaration just as var is added to the beginning of a variable declaration.
  • addOneToSomeNumber is the name of our function.
  • The brackets are for the inputs of the function. Although this function involves no inputs, we still have to add the brackets.
  • The :void part is for the output of the function. Normally, void would be replaced by the data type of the output. Since this function involves no outputs, we use the keyword void instead.
  • The opening brace marks the beginning of a block.

The second line is known as the signature of the function. It contains important information about the function.

Now let's trigger, or call, the function:

public function Main():void{
     //...
     addOneToSomeNumber();
     //The value of someNumber is now 6.
     addOneToSomeNumber();
     //The value of someNumber is now 7.
}

As you can see, to call a function, simply type the function identifier, followed by a pair of brackets.

How can I declare and call a function with inputs?[edit | edit source]

In programming, the 'fields' of a function are called parameters and the values passed through the parameters are called arguments. Let's modify our addOneToSomeNumber function to accommodate the addition of any number to someNumber:

private var someNumber:Number = 5;
private function addAnyNumberToSomeNumber(anyNumber:Number):Void{
    someNumber += anyNumber;
}

In this example, the code anyNumber:Number is put into the brackets. This is the input of the function and is written as variableName:DataType. Once input, anyNumber automatically becomes a local variable.

To call the function addAnyNumberToSomeNumber, we only need to put the value inside the bracket. The data type is not needed!

public function Main():void{
     //...
     //The original value of someNumber is 5.
     addAnyNumberToSomeNumber(4);
     //The value of someNumber is now 9.
     addAnyNumberToSomeNumber(2);
     //The value of someNumber is now 11.
}

Does this give you a feeling of déjà vu? It should! Remember these lines from the first class we saw?

                        removeEventListener(Event.ADDED_TO_STAGE, init);
                        trace(HELLO_WORLD);
                        trace("Your name is " + name + ".");

They are all function calls! trace is a top-level function that outputs a string in the output window. It is very useful for debugging and is only available in debug builds.

Now let's modify our code to have two inputs:

private var someNumber:Number = 5;
private function addTwoNumbersToSomeNumber(firstNumber:Number, secondNumber:Number):Void{
    someNumber += firstNumber + secondNumber;
}
public function Main():void{
     //...
     //The original value of someNumber is 5.
     addAnyNumberToSomeNumber(4, 3);
     //The value of someNumber is now 12.
     addAnyNumberToSomeNumber(1, 2);
     //The value of someNumber is now 15.
}

The comma is used to separate the two parameters. This also works with three parameters or more.

How can I declare and call a function with outputs?[edit | edit source]

Look at our addAnyNumberToSomeNumber code again. Suppose we don't want to touch the original variable, but want to get the sum of anyNumber and someNumber anyway. That's where a function with a return value comes in handy.

Code Result
var someNumber:Number = 5;
function addTwoNumbers(originalNumber:Number, anyNumber:Number):Number{
    return (originalNumber + anyNumber);
}
trace(addTwoNumbers(someNumber, 7));

12

In this function, the value of someNumber was passed on, but instead of changing someNumber, the function returns the sum of someNumber and 7 directly to the trace function.

Note that since this function contains only a return statement and nothing else, it would not make sense to call the function as a separate statement:

var someNumber:Number = 5;
function addTwoNumbers(originalNumber:Number, anyNumber:Number):Number{
    return (originalNumber + anyNumber);
}
addTwoNumbers(someNumber, 7);

See, nothing happens! The function is good for returning a value, but nothing else.

Also note that functions in return values can be used in a variety of versatile ways that is not limited to tracing. For instance, look at the following code:

Code Result
var someNumber:Number = 5;
function addTwoNumbers(originalNumber:Number, anyNumber:Number):Number{
    return (originalNumber + anyNumber);
}
var yetAnotherNumber:Number = 6 / addTwoNumbers(someNumber, 7);
trace(yetAnotherNumber);

0.5

In this script, the computer first evaluates the value addTwoNumbers(someNumber, 7), which equals 12. It then performs the operation 6 / 12, and finally assigns it to yetAnotherNumber.

To conclude, the syntax for declaring a function is as follows:

function functionName(parameter1:DataType1, parameter2:DataType2...):ReturnDataType{
    Statements;
    return value;
}

How can I call a function with no inputs and no outputs?[edit | edit source]

In order to use a function, we need to call it. Let's look at the above example again:

Code Result
var someNumber:Number = 5;
function addOneToSomeNumber():Void{
    someNumber++;
}
addOneToSomeNumber();
trace(someNumber);

6

In the function call above, we just called the function addOneToSomeNumber. The bracket after it is for the inputs of the function, which we'll cover in the next section. The computer performed the function, which involves increasing someNumber by 1. That's how we got the result 6.

How can I declare and call a function with inputs?[edit | edit source]

How can I declare and call a function with an output?[edit | edit source]

How should I name my functions?[edit | edit source]

Like variables, you cannot use reserved words for functions, and the functions can only start with a letter. According to established naming conventions, good function names start with a action verb which can be concatenated with other words using CamelCase. Examples include eatWatermelon(), drinkWater() and smashVase().

What are callers and callees?[edit | edit source]

When a function is called, it is called a callee. When a function is called by another function, the calling function is called the caller.

The arguments object of a function can find the caller and the callee. The following example traces the caller and callee:

Code Result
function uselessFunction():Void{
     trace(arguments.caller);
     trace(arguments.callee);
}
uselessFunction();

[type Function]
[type Function]

Note that since functions cannot be represented in textual form, the computer traces [type Function], which just indicates that it's a function.

Can I put a function in a variable?[edit | edit source]

If you really want to, you can put a function inside a variable. Here's the syntax:

var variableName:Function = function(parameter1:DataType1, parameter2:DataType2...):ReturnDataType{
   Statements;
   return value;
}

Here's an example:

Code Result
var someFunction:Function = function(someString:String):Void{
	trace(someString);
}
someFunction("Hello world!");

Hello world!

Wait, then what's the deal with the trace function?[edit | edit source]

By now, you may be wondering where you got the trace function when you've never defined it anywhere. Read the next chapter to find out!

Notes[edit | edit source]