Introducing ActionScript Functions

Flash ActionScript | Beginner | By Blue_Chi

Functions are a powerful feature in ActionScript that make it possible to reuse blocks of code throughout a flash movie in great flexibility. Using functions saves the programmer a massive amount of time, they can be used to centralize the code so that everything can be controlled, edited and updated from a single point and they also make the code much more easier to read by other people. There are two types of functions in ActionScript: built-in functions and custom functions. This tutorial involves the creation and invocation of custom functions.

Function example:

function functionName (param1, param2, etc...) {
statements
}

A function can be created by using the function keyword followed by the function name (we make this ourselves) . The parenthesis contain any optional parameters, and the statements inside the curvy brackets are the blocks of code to be reused.

There are two stages for using a function; declaration and invocation. To be able to use (invoke) a function, you have to first define (declare) it. For example, lets define a function to move a square movie clip.

function moveSquare () {
mySquare._x += 10;
mySquare._y += 10;

}

moveSquare is the name we have chosen for the function and it will be used later to invoke the function. mySquare is the instance name of a square movie clip I have on the stage. The codes used make the square move both horizontally and vertically an extra 10 pixels. To invoke the function at any later frame we write the name of the function followed by the parenthesis:

moveSquare ();

Now every time we write down that, the square movie clip will move. If we wanted to move the square at different places on the timeline we would have had to write the same code several times, but this way makes it possible for us to write the actual code once inside the function and then just invoke the function by typing down its name. Using function saves time and coding space.

That was not all, functions are much more powerful than this. If you notice the very first example we put, the parenthesis can hold optional parameters. These parameters are to be defined on the invocation of the function each time. For example, we can make a function to move "an object" but we can make the name of the object changeable:

function moveObject (myObject) {
myObject._x += 10;
myObject._y +=10;

}

This way when we invoke the function we can define what the variable myObject is this way to move a square on the stage with an instance name of mySquare:

moveObject (mySquare);

If we wanted to use the same code to move ANY other object we simply put its instance name within the parenthesis and it should work!

moveObject (myCircle);

Functions can be much more complex than this, but this is their very most basic function. Here is a quick list with important notes about functions:

End of Tutorial

x