So you understand using Variables and the different types of Flow Control using different Actionscript constructs. The next thing we should talk about are Functions.
A Function is a great example of reusable code. It can simply do something whenever you call it... (That kind of Function is sometimes called a "Procedure"), or it can take input variables, called "Parameters", and optionally, it can return a result to the code that invoked the Function, called a "Result".
The syntax of a Function is pretty straightforward:
function functName(param1:type, param2:type, etc):ResultType {
//function code
return Result; //optional
}
Here are a couple of examples of Functions:
// A function to reset all of the variables in a game program when a new game is started.
function initializeGame():Void {
currentScore=0;
playerName="";
characterArray=new Array();
ready=true;
}
The word Void is optional in this case, but is good coding practice. It means that this particular function does not return any result.
// A function to find the length of the hypotenuse of a right triangle.
// side1 squared plus side2 squared = hypotenuse squared
function hypotenuse (side1:Number, side2:Number):Number {
return Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
}
In this example, we are passing two parameters, both of which are numbers (we're passing the length of the two known sides of the triangle). We are also using some built-in Actionscript Math functions:
Math.sqrt- returns the square root of the passed numberMath.pow- returns the result of the first number raised to the power of the second number.
Functions can be much more complex than these examples, but this should give you a good start. Functions should be used when you have blocks of code that get used a lot, or similar code that can be collapsed into a single function that uses input parameters.
Transforming your programs with the use of Functions is as easy as adding a new code of paint! 