3. Working with Functions

When you work with ActionScript, there are sequences of code that you may want to execute multiple times. To do this, you need a way to group the code into a logical block and give it a name that will tell the Flash runtime to execute the code.

Functions are the way to do exactly that. Using functions, you can group commonly used commands for repetitive use throughout your application. In this chapter, you’ll learn the commands and syntax to create a basic function, and then learn how you can extend the use of your functions to send and receive data in and out of them.

Fundamentals of Functions

To get started with functions, let’s look at the following example.

1. Create a new ActionScript 3.0 Flash file and enter the following code into the frame script on the timeline:

function runMe():void
{
    trace("The function runMe was executed.");
}
runMe();

2. Run the code. The phrase “The function runMe was executed” appears in the Output panel in Flash (Figure 3.1).

Figure 3.1. Results from your first function

image

Let’s walk through the code and explain how it works, referring to the numbered elements in Figure 3.2.

Figure 3.2. An example function with callouts

image

First, the function statement image tells Flash that you are starting a new named function that will contain a number of commands or statements. After the function statement, you need to provide a name for this group of commands so you can access them later. In this case, you are using the name runMe image. You finish the function definition with a pair of parentheses image and with the text :void that you’ll learn about in a bit image.

The statements that are part of the function need to be wrapped with a matching set of curly braces image. Inside these braces are the statements that are part of the function. Notice that Flash indents these lines of code for you automatically. Using tabs to indent code that is placed within curly braces is a best practice. This makes the code easier to read and makes identifying code that is part of code blocks quicker. The tabs are called white-space characters.

The last line is the function call image. To tell Flash to run the contents of a function code block, you need to refer to the function name followed by a pair of parentheses. Since this is a single line of code, you need to end it with a semicolon.

Notice that the function line and each of the curly braces do not have semicolons at the end. They are not required on these lines. In fact, they would cause an error. Only the lines within the curly braces that define the code block should end in semicolons.

As you work with other programmers, you may see the curly brace locations shift from time to time. Their exact position is not critical, but they need to be in the correct order. For example, the following two functions are identical to the previous example, but are formatted just a bit differently:

// Example 1 – Opening curly brace on function line
function runMe():void {
    trace("The function runMe was executed.");
}
// Example 2 – Opening curly brace on line below function
function runMe():void
{
trace("The function runMe was executed.");
}
// Example 3 – All white space removed
function runMe():void { trace("The function runMe was executed."); }

This is an example of how white-space characters (spaces, tabs, or line breaks) don’t affect the function of the code, but can be used to make code look cleaner; all three examples will run the same way.

Accepting Values in Functions

In the previous example, the function did not request or submit any information back to the program, it simply executed a sequence of commands. By adding a few options to the function, you can have it change its functionality based on values that are submitted to it.

In this example, you’ll start by creating an object in the Library that you can access using ActionScript:

1. Create a new ActionScript 3.0 project.

2. Create a blue circle on the Stage and convert it to a MovieClip symbol, activating the Export for ActionScript option in the ActionScript Linkage section. Call the object Blue Circle, which will automatically output as BlueCircle.

3. Remove the symbol that was just converted on the stage. You won’t need it..

4. Open the Actions panel and add the following code to your timeline:

// Create new BlueCirle instance
var circle:BlueCircle = new BlueCircle();
circle.x = 50;
circle.y = 50;
addChild(circle);
// Reposition function
function reposition(newX:Number):void
{
    circle.x = newX;
}
// Reposition circle
reposition(100);

Figure 3.3. Library with the BlueCircle linked object and the Actions panel

image

In this example, you are placing an object on the Stage and are accessing the function reposition(). To change the behavior of the function, you are passing a value to the function.

For a function to accept a value, the function declaration needs to have the required parameters expressed inside the parentheses, and it needs to have a name it can give the parameter for the duration of the function. The function also needs to know what type of object the parameter is. In this example, the new name for the parameter is newX and is defined as a number by adding :Number after the name. This temporary value will be thrown away when you’re finished with the function. It exists only while the function is running.

You might be asking yourself what the :Number and :void mean in your ActionScript. When working with functions, ActionScript needs to know the type of data that is going in and out of it. In this case, you are defining that newX will be a number, which is a data type in ActionScript. There are a lot of data types that ActionScript can use. The Number type includes any number that is a decimal value that is either positive, like 123.45, or negative, like -234.56. The :void statement indicates that there isn’t any data being used, meaning it is “void” of data. You’ll learn more about data types in the future, but that sums up the types in this example.

Now, in order to pass this value to the function when it is run, you need to specify the parameter value within the parentheses when you call the function.

Refer to the numbered elements in Figure 3.4 while walking through this in more detail.

Figure 3.4. Example function that accepts a parameter with callouts

image

You have defined a function that requires a number parameter called newX for the duration of the function image.

You call the function reposition() and pass in the value of 100 image.

The function gets that value, verifies it is a number, and assigns it to the name newX image.

The function runs, overwriting the x attribute of the circle object with the value of newX, and then ends the function since there are no other statements before the closing curly brace image.

The result when you run the project looks like Figure 3.5.

Figure 3.5. Result of the code using the reposition() function.

image

Possible Errors when Working with Functions

When running a function, there are a couple of ways that you could inadvertently get an error: failing to send a required parameter and sending the wrong value type.

Required Parameter Error

When you define a parameter, the parameter is required by default, but there are ways to make a value optional. If you fail to pass in a value to the function, you’ll get an error.

The following example shows how the missing parameter error occurs:

1. Modify your code to remove the 100 within the reposition() function call on the last line. It should read like this:

// Reposition circle
reposition();

2. Run your project again.

3. Look at the Compiler Errors panel that will display. You’ll see the following error display:

1136: Incorrect number of arguments.  Expected 1.

This error is indicating that you are executing a function that requires a parameter or argument, but in this case you failed to send one.

Type Mismatch Error

Another type of error occurs if you pass in a value of the wrong type. Remember that the :Number statement indicates that newX is of the Number data type. If you pass in a string to the function, you’ll get a type mismatch error.

The following example shows how the type mismatch error occurs:

1. Modify the reposition() function and add a string within the parentheses. It should read like this:

// Reposition circle
reposition("100");

2. Run your project again.

3. Look at the Compiler Errors panel that will display. You’ll see the following error:

1067: Implicit coercion of a value of type String to an
unrelated type Number.

To correct this, check your code and make sure you are using the right format for your function parameter value. You can adjust either the value you are passing in or the type of value that the function is expecting.

Returning Values from Functions

In this last example, you’ll look at how to make the function return a value to the location from which it was called. Let’s look at a new example. Here is some example code for a new project:

// Send greeting to Output panel
trace( generateGreeting("Doug") );
// Function to generate a greeting message
function generateGreeting(firstName:String):String
{
    return ("Welcome, " + firstName + "!");
}

In this code is a trace statement that is calling a function instead of providing a variable name or a string that would be sent to the Output panel. When you use a function name in this way, you are asking the function to run and replace the function name with the value it returns.

The function itself is similar to the previous examples; however, it is requiring a string value as its required parameter. After the parameter definition and at the end of the function declaration, you have :String. In previous examples, you used :void at the end to signify that the function didn’t return any value when it was finished. That is no longer true; this time the function will return a string when it is finished.

Inside the function is a new command, the return statement. The sole purpose of the return statement is to send a value back to the calling location of the function; in this case, inside the trace statement.

The return statement is followed by an expression, where you are combining strings together. This is also called concatenation. You can combine strings together by using the plus sign (+) to link them together. You are also using the variable firstName, which is a temporary container for the value sent to the function, in this case the word “Doug.” The return statement sends the concatenated string back to the calling location and ends the function. The return statement ends the function, regardless of whether there are commands after it.

Figure 3.6 shows the result.

Figure 3.6. Welcome!

image

Refer to the numbered elements in Figure 3.7 while running through this example.

Inside the parentheses for the trace statement, you run the function generateGreeting() instead of providing a string or variable image.

Figure 3.7. Example function with a return statement

image

That function runs and accepts the value "Doug" as its parameter value and assigns it to the firstName variable for the duration of the function image.

Inside the return statement, you combine three strings together to form a single string “Welcome, Doug!” using the + operator to concatenate the strings, and then exit out of the function with the return statement sending the single string back to the original call image.

Back in the trace statement, with the function returning a value, the function call itself is replaced by the contents from the function. The trace statement executes, sending the string to the Output console image.

If you failed to use the return statement, you would get the following error:

1170: Function does not return a value.

When you define a return type, in this case String, you must return this type of value from the function. Otherwise, you will get the 1170 error above. If you have a function that doesn’t return a value, make sure you always define its return type as void.

More about Parentheses (and Curly Braces)

You’ll notice that the previous code example uses a lot of use of parentheses. For example, this line:

trace( generateGreeting("Doug") );

Parentheses, and also curly braces, are important for grouping things that you want to evaluate together. In this case, you have the phrase “Doug” being evaluated with the generateGreeting() function. This is the evaluation within the trace statement that sends the returned value to the Output panel.

What can sometimes trip up coders when they first start in ActionScript is to forget to have matching parentheses pairs, as in the following example:

trace( generateGreeting("Doug");

If you attempt to run this code, you’ll get the following error in the Output panel:

1084: Syntax error: expecting rightparen before semicolon.

This error indicates that you are missing a parenthesis. The parentheses around "Doug" are correct, but you have failed to add a closing parentheisis for the trace statement.

Wrestling with parentheses and curly braces is something that every coder needs to deal with. Make sure you double-check your opening and closing parentheses and curly braces to ensure that they are all matched correctly.

Wrapping Up

Functions are one of the most commonly used features of ActionScript, and you’ll be using them over and over again. All functions share the same basic rules, regardless of their function or use in your application. Here are some general rules to keep in mind when working with functions:

• All functions begin with the function statement and have a name associated with them.

• All code that is part of a function is enclosed within a code block, denoted by opening and closing curly braces.

• Any values that you can send into a function must be declared within the function definition, inside the parentheses. All values must have a name that will be used to represent the values during the function, and the values must have a type.

• Every function must either define what type of value it will return or define that it will return nothing by using a return type of void.

• When working with parentheses, make sure they are all properly closed (matched) to avoid any errors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.200.76