NOTE: This page is still about AS2. It has not been fully upgraded to AS3. |
| Introduction to ActionScript 3.0 | ||
| Variables and Data Type | Functions | Operators |
Key concepts:
Now that we've learnt all our operators, we can get to the next part: functions.
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, afunction 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:
We'll discuss each type of function in the following text. First, we'll have to learn to construct and 'call' functions.
Here's a simple function with no outputs and no inputs. Look at the code and we'll explain it step by step:
privatevarsomeNumber:Number=5;privatefunctionaddOneToSomeNumber():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 asvar is added to the beginning of a variable declaration.: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 keywordvoid instead.The second line is known as thesignature of the function. It contains important information about the function.
Now let's trigger, orcall, the function:
publicfunctionMain():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.
In programming, the 'fields' of a function are calledparameters and the values passed through the parameters are calledarguments. Let's modify our addOneToSomeNumber function to accommodate the addition of any number to someNumber:
privatevarsomeNumber:Number=5;privatefunctionaddAnyNumberToSomeNumber(anyNumber:Number):Void{someNumber+=anyNumber;}
In this example, the codeanyNumber:Number is put into the brackets. This is the input of the function and is written asvariableName: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!
publicfunctionMain():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:
privatevarsomeNumber:Number=5;privatefunctionaddTwoNumbersToSomeNumber(firstNumber:Number,secondNumber:Number):Void{someNumber+=firstNumber+secondNumber;}publicfunctionMain():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.
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 |
|---|---|
varsomeNumber:Number=5;functionaddTwoNumbers(originalNumber:Number,anyNumber:Number):Number{return(originalNumber+anyNumber);}trace(addTwoNumbers(someNumber,7)); |
|
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:
varsomeNumber:Number=5;functionaddTwoNumbers(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 |
|---|---|
varsomeNumber:Number=5;functionaddTwoNumbers(originalNumber:Number,anyNumber:Number):Number{return(originalNumber+anyNumber);}varyetAnotherNumber:Number=6/addTwoNumbers(someNumber,7);trace(yetAnotherNumber); |
|
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:
functionfunctionName(parameter1:DataType1,parameter2:DataType2...):ReturnDataType{Statements; returnvalue;}In order to use a function, we need tocall it. Let's look at the above example again:
| Code | Result |
|---|---|
varsomeNumber:Number=5;functionaddOneToSomeNumber():Void{someNumber++;}addOneToSomeNumber();trace(someNumber); |
|
In the function call above, we just called the functionaddOneToSomeNumber. 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.
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().
When a function is called, it is called acallee. When a function is called by another function, the calling function is called thecaller.
Thearguments object of a function can find the caller and the callee. The following example traces the caller and callee:
| Code | Result |
|---|---|
functionuselessFunction():Void{trace(arguments.caller);trace(arguments.callee);}uselessFunction(); |
|
Note that since functions cannot be represented in textual form, the computer traces [type Function], which just indicates that it's a function.
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 |
|---|---|
varsomeFunction:Function=function(someString:String):Void{trace(someString);}someFunction("Hello world!"); |
|
By now, you may be wondering where you got thetrace function when you've never defined it anywhere. Read the next chapter to find out!