Jump to content

Introduction to ActionScript 3.0/Functions

From Wikibooks, open books for an open world
Introduction to ActionScript 3.0
Variables and Data Type Functions 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]