gavin sim logo
 

Basic - week 1

Week 2

Week 3

Week 4

Week 5

Week 6

Week 7

Teaching > Flash notes

Functions

Quick Example

Create a new flash document and on the first frame type the following code:

var myname:String="gavin";

function who():void{
   trace("Your name is "+ myname);
}
who();

If you Control / Test Movie you will see that in the output window Your name is gavin. The first line creates a variable with a datatype string, the void indicates no return value and the trace simply displays the output. To call the function you have the who() at the bottom.

Quick example part 2

Create a new flash document and on the first frame type the following code:

var myname:String="gavin";
function who(person:String):void{
   trace("Your name is "+ person);

}
who(myname);

If you control / test movie you will get the same output as the previous example. The main difference is that the variable myname is being passed to the function, this is then assigned to a local variable (this only exists in the function) named person. The trace staement uses the local variable person instead of myname.

Quick example part 3

Create a new flash document and on the first frame type the following code:

var county:String = "lancashire";
var country:String = "unknown";

function locationIs(place:String):String {
   if (place=="lancashire"){
      country = "england";
      return country;
   } else {
      return country;
   }
}

var where:String = locationIs(county);
trace(where);

Control / Test movie and England will be displayed in the output window. The code is slightly more complex than the previous examples. You start of with two variables then the function locationIs is declared with the name locatioIs. Within the parentheses is the variable place with a datatype of string, after the end bracket is another String this indicates that the function will return a String value when called.

There is then a conditional which determines whether the variable place is equal to lancashire, if this is true then england is returned else unknown is returned.

The second to last line has a variable where which is a string type and this is equal to the returned value from the function.

Excercise

See if you can write a function similar to the last example which will add 4 numbers together and return the value to a variable named total.