In this lesson there are presented more advanced things about using functions.
The exemples in this tutorial use an Instance of a Movie Clip symbol created on the Stage (in Flash).
So, before to start testing the exemples below, open a new Flash document, select "Rectangle tool" and draw a rectangle on the Stage, then convert it in Movie Clip symbol (from Modify -> Convert to Symbol, and for Type select "Movie Clip").
Make sure the object is selected, open the "Properties panel" and add a name for this instance, testClip, like in the picture below.
testClip instance

Setting parameters with default value

In ActionScript 3.0, you can set default values for a function's parameters. To do this, simply add an equal sign (=) and the default value after an parameter name, as follows.
function sayHy(name:String = 'You') {
  trace('Nice to meet '+ name);

sayHy('Marius');        // displays:  Nice to meet Marius
sayHy();        // displays:  Nice to meet You
- As you can see, the parameter with a default value becomes optional, you can call the function without adding an argument for that parameters. If you not pass an argument, the function will use it with the default value.

All parameters that have a default value must be placed last in the order of arguments.
              function setAccount(name:String, pass:String, email:String = null)

Let's test another example, using the "testClip" instance (the rectangle created at the beginning of this lesson).
In the same document in which you have created the rectangle, right-click on Frame 1 in the Timeline, and choose Actions. Then, in the "Actions panel" add the following code:
// define a function with 2 parameters, the second is default
function testF(dy:Number, rotatie:int = 45):void
  // sets "y" and "rotation" properties for "testClip" instance
  testClip.y = dy;
  testClip.rotation = rotatie;

// call the function, passing only the required argument (dy)
- "testClip.y" sets the Y distance, "rotation" is a property used to rotate the object.
Press "Ctrl+Enter" to see the effect of this script. The Flash player will position and rotate the rectangle, like in the image below.
testClip instance 2
To download the FLA file with this example, click testClip Example.

Using the rest parameter (...)

ActionScript 3.0 adds a new feature called the rest parameter.
The "rest parameter" is a symbol (...) that represents a variable number of arguments as an array followed by a name for that array (... array_name). "array_name" will be used for the array containing the values.
The rest parameter allows you to call a function with as many arguments as you like; their values will be stored in the "array_name" Array.

Here is an example (it uses the same document in which you have created the "testClip" instance).
- Right-click on Frame 1, and choose Actions. Then, in the "Actions panel" delete any existing code and add the following code:
// define a function with "rest parameters"
function testF2(... nums):void
  // declare a variable which will be used to store the sum of the values passed in arguments
  var latura:Number = 0;

  // define a "for" to access each value stored in "nums" Array
  for each (var num:Number in nums)
    latura += num;        // add the current value to "latura

  // uses the variable, "latura" to set the 'width' and 'height' for "testClip"
  testClip.width = latura;
  testClip.height = latura;

testF2(8, 20, 40, 50);          // calls the functions with multiple arguments
- All values passed to the "testF2()" function are stored in the "nums" Array.
- The "width" and "height" properties sets the width and the height of the object (in this case with a value of 118, 8+20+40+50 = 118).
Press "Ctrl+Enter" to see the result. The rectangle on the stage becomes a square, like in the picture below.
testClip instance 3
To download the FLA file with this example, click testClip Example 2.

The rest parameter can also be used with other required parameters. The required parameters will have their own names and will exist independent of the rest array. Any additional arguments passed after the required ones will be stored in the rest array.
              function test(param1, ... rest_array)

Assign function to a variable

Another way to define a function is to assign it to a variable of type Function.
The syntax is:
var someVariabe:Function = function (param1, param2, ...) {
  // code to execute
- Once assigned, the function can then be invoked through that variable, as in:
someVariabe(arg1, arg2, ...)
Because the function is assigned to a variable, it resides in memory as any normal variable. So, the value of this variable can be changed or deleted.

- Add the following code in the Flash document in which you have created the instance "testClip" (delete any other ActionScript code in Actions panel), then press "Ctrl+Enter".
// define a function with 3 parameters in a variable
var vrF:Function = function (obj:MovieClip, sx:Number, sy:Number):*
      // "obj" must be the instance of a MivieClip
      // define "scaleX" and "scaleY" properties for "obj
      obj.scaleX = sx;
      obj.scaleY = sy;

// call the function, passing the 'testClip' instance for the "obj" parameter
vrF(testClip, 2.5, 1.4);
- the variable name (vrF) its the name used to call the function.
- "scaleX" and "scaleY" multiply the width and height of the object.

Variables and Functions

The variables declared outside a function (before the function definition) can be used in the function code.
The variables created within a function can only be used inside the code of that function. These variables are called "local variables", and they not exists outside the function.

Example (see the comments in code):
var ext_vr:int = 18;        // variable created outside any function

// define a function which use the "ext_vr" variable
function oFunctie():Number
  // create a local variable
  var in_vr:Number = 7;

  // add the value of the external variable "ext_vr" to the local variable
  in_vr += ext_vr;

  return in_vr;        // return the values of "in_vr"

trace(oFunctie());      // displays in Output the value returned by the function (25)

// Try to access the local variable "in_vr" outside the function (delete "//")
// trace(in_vr);
- Notice that the oFunctie() can use the value of the external variable "ext_vr". But if you try to access the local variable "in_vr" outside the function (deleting the "//" before trace(in_vr);), you'll get an error message.

Recursive Functions

A recursive function is a function that calls itself.
To avoid infinite recursion (when a function never stops calling itself), use an "if()" condition to control when a recursive function calls itself.
One classic use of the recursive functions is to calculate the mathematical factorial of a number, which is the product of all positive integers less than or equal to the number (1*2*3*4*...*n).
In the next example it is created a recursive function to calculate the mathematical factorial of a number passed in argument.
// define a recursive function
function factorial(n:uint):uint
  // if n>0, multiply 'n' auto-calling function
  if(n > 0)
    return (n * factorial(n-1));
  else { return 1; }       // return 1 when n>0 is false

// store in a variable the value returned by factorial(8)
var fact:uint = factorial(8);

trace(fact);          // Output:  40320

Daily Test with Code Example

Which tag adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
Click on the "echo" correct instruction.
echo "" echo ""; echo """;
echo "Address URL:";
Functions - Advanced Use

Last accessed pages

  1. Sport Games (5629)
  2. Logic Perspicacity Games (5739)
  3. ActionScript 3 Lessons (4748)
  4. Adobe Flash - ActionScript 3 Online Video Course and Tutorials (2057)
  5. Tic Tac Toe Note Paper (182)

Popular pages this month

  1. Qwop (4652)
  2. Bubbles3 (3754)
  3. Butterfly Kyodai (3124)
  4. Drag Racer V3 (3079)
  5. Zuma Deluxe (2227)