
Beginning ActionScript 2.0 2006
.pdf
Chapter 3
var i:Number = 0;
while (paragraphText.charAt(i) != stopCharacter)
{
sentenceText += paragraphText.charAt(i); i++;
}
trace(“Sentence: “ + sentenceText);
To understand what is causing an infinite loop here requires some knowledge of the data and of the logic flow. This code goes through each character in the input string looking for a period. Once it finds a period, it quits. The problem is that the data has no periods, and the code does not test to see if it has run out of data to check. Inserting a trace() statement may not work, because the first trace statements (the ones you need to see) will likely scroll out of the output area.
If you can’t see what is causing the problem, you might need to step into the debugger. Here’s how:
1.Create a new Macromedia Flash document by selecting File New and choosing Flash Document from the New Document panel.
2.Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the preceding ActionScript code.
3.Right-click the line with the while statement and select Set Breakpoint, or click the line number. A red dot should appear on the left (see Figure 3-5).
4.
5.
Figure 3-5
Select Control Test Movie. The debugger panel appears.
Click _level0 in the top-left pane of the debugger panel.
78

Understanding ActionScript Expressions and Loops
6.Click the variables tab in the middle-left pane of the debugger panel (see Figure 3-6).
Figure 3-6
7.Click the green arrow at the top of the main debugger panel. Click a few more times while watching the values in the variables section change.
One of the things you will see is that i constantly increases in value, even after the last letter has been examined.
The solution to this is to be more careful about dealing with different data conditions. Doing an additional check to see if the end of the array has been reached would resolve this issue:
var stopCharacter:String = “.”;
var paragraphText:String = “The quick brown fox”; var sentenceText:String = “”;
var i:Number = 0;
while (i < paragraphText.length && paragraphText.charAt(i) != stopCharacter)
{
sentenceText += paragraphText.charAt(i); i++;
}
trace(“Sentence: “ + sentenceText);
//Outputs:
//Sentence: The quick brown fox
79

Chapter 3
Summar y
You are now getting into the thick of learning the core ActionScript language. Some points to remember include the following:
Decisions in code are made through working with the if..then..else and the switch..case conditionals.
A conditional is a combination of an expression made up of one or more operators, plus a block of one or more statements that are executed if the result of the decision is true.
The for, for..in, while, and do..while loops enable you to work with repeating data.
The for loop is perfect for working with indexed arrays.
The for..in loop works for iterating through data in an associative array.
The while loop is used when you do not initially know how many times that the loop should iterate. It stops when a condition or a set of conditions has been met.
Off-by-one errors involve situations in which there is a miscount in the number of times a loop should iterate. This error can be avoided in the for loop by sticking to the syntax for (var i:Number = 0; i < arrayLength; i++).
Infinite loops result when the condition that is supposed to stop the loop never takes place. The debugger is frequently helpful in figuring out what is happening in an errant loop.
Exercises
1.With the following shopping cart data, create an array that stores the data, and then create a loop that traces out each piece of data and prints out a total dollar amount.
Purchased one MP3 music player, model number ip300, priced at $299.
Purchased one player case, model number ip300c, priced at $49.
Purchased two sets of earbuds, model number eb100, priced at $29 each.
Purchased a car charger kit, model number cc250, priced at $69.
2.Convert the following if..then statement to a switch..case statement:
var vehicleType:String = “semi”; var spareCabin:Boolean = false; var numDoors:Number;
if (vehicleType == “sedan”)
{
numDoors = 4;
}
else if (vehicleType == “sportscar”)
{
numDoors = 3;
}
else if (vehicleType == “semi” && spareCabin == true)
80

Understanding ActionScript Expressions and Loops
{
numDoors = 3;
}
else if (vehicleType == “semi” && spareCabin == false)
{
numDoors = 2;
}
else
{
numDoors = 2
}
trace(numDoors);
3.Convert the following while statement to a for statement:
var fruitArray:Array = new Array(“banana”, “pear”, “strawberry”, “grape”); var numFruit:Number = fruitArray.length;
var currentFruit:Number = 0; var foundFruit:Number = 0; var numLetters:Number = 6;
while (currentFruit < numFruit)
{
if (fruitArray[currentFruit].length >= numLetters)
{
trace(fruitArray[currentFruit]);
foundFruit++;
}
currentFruit++;
}
trace(“found “ + foundFruit + “ fruits with 6 or more letters in the name”);
81


4
Exploring ActionScript
Functions and Scope
Several critical aspects of programming include reusability, organization, and understandability. Reusability enables you to take a section of code and to apply it in numerous places within your program and within other programs. Organization allows code to be found easily, and to have different sections of code relate in ways that make sense. Understandability means that your code still makes sense when you return to it after several weeks.
This chapter introduces you to ways of organizing your code so that it is logically structured, easy to read, and easy to reuse.
Functions
The code snippets used in this book so far have been quite short, and have been written in sort of a stream-of-thought style. As programs get larger, code reusability, organization, and understandability become essential.
The first step toward this goal is the proper use of functions. A function is a reusable grouping of code that performs a single task. A function may require data to be passed in as arguments, and a function may return data as a result of some computation.
Say that you need to write some code that includes formatting an email address, and that several places within the code need such formatting. Rather than duplicating the code that is responsible for the formatting, you write it once in a function. Wherever an email address needs to be formatted in your program, the function is called to handle it. The function acts as a reusable container that saves you effort, and in this case allows for any later changes in the formatting routine to be done in one place rather than in several places.

Chapter 4
The general form for declaring a function is as follows:
function functionName(inputValue:DataType):ReturnType
{
// Statements return <value>;
}
First, the function keyword indicates that what follows is a function definition. It’s followed by the name of the function, which is something that you make up, and should reflect the function’s intended purpose. A function name can consist of any combination of letters, numbers, and the underscore character, but it cannot start with a number, and it cannot be the same as a reserved word. Function names are case sensitive, so emailformat() and emailFormat() are two different functions.
A pair of round brackets immediately follows the function name. Any input parameters that the function should accept go inside the brackets. A function can define as many input variables as are needed. If none is needed, the round brackets are empty; otherwise they contain a comma-separated list of variable names and variable data types. The variable names can be anything: they are just placeholders to refer to within the function. The data type reflects the kind of data that the variable will contain, such as Boolean, Number, or String. The compiler uses this data type information to ensure that when the function is called, the data that is passed in is consistent with the data types that have been defined (if it isn’t, the compiler halts and gives an error).
At the end of the first line, the return type defines the kind of data the function sends back, if any. If a return type is defined, there must always be at least one return statement. The return statement immediately stops the function and sends back a value. If the function is not to return any data, you set the return type to the keyword Void.
Finally, a pair of curly brackets follows the function declaration. Any code placed between the brackets executes when the function is called.
To call a function, the general syntax is as follows:
var returnVar:ReturnType = functionName(inputValue);
Or if no data is to be returned from the function:
functionName(inputValue);
Here, inputValue is a variable representing data that needs to be passed to the function, which in turn sends the result of the call back to the variable returnVar.
Here’s an example that illustrates how functions are used:
function formatEmailAddress(userName:String, domainName:String):String
{
return userName + “@” + domainName;
}
var email1:String = createEmailAddress(“jsmith”, “somedomain.com”); trace(email1);
84

Exploring ActionScript Functions and Scope
// Outputs: jsmith@somedomain.com
var email2:String = createEmailAddress(“bhill”, “somedomain.com”); trace(email2);
// Outputs: bhill@somedomain.com
This function declaration defines input parameters for a username and a domain name. The two input parameters are combined into a properly formatted email address, which is then sent back as a return value. The function is called twice, with different usernames, and each result is assigned to its own variable. The trace() statements show that those two variables contain the formatted email addresses.
Here’s a more complicated example. One task that you might need in any number of projects is to get the current time in a particular format, such as with just hours and minutes. This function takes care of the formatting, so that you only have to call the function whenever you need the current time:
function getCurrentTime():String
{
var currentTime:Date = new Date(); var currentTimeString:String = “”;
currentTimeString = String(currentTime.getHours()) + “:”;
if (currentTime.getMinutes() < 10)
{
currentTimeString += “0” + String(currentTime.getMinutes());
}
else
{
currentTimeString += String(currentTime.getMinutes());
}
return currentTimeString;
}
var currentTime:String = getCurrentTime(); trace(currentTime);
// Outputs 14:34
The getCurrentTime() function takes no parameters; it just gets the current time and returns the hours and minutes as a string formatted in the international 24-hour time format. If the data type in currentTime:String were to be changed to something else, such as currentTime:Number, the compiler would give an error:
**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 149: Type mismatch in assignment statement: found String where Number is required.
Total ActionScript Errors: 1 |
Reported Errors: 1 |
The compiler is reporting that getCurrentTime() returns a String, but the variable assigned to the return data expects a Number. This error message is actually a very good thing! The compiler is telling you right off the bat that you’re working with incompatible data types. Without this validation, data errors could show up later on, and would likely require significant time to track down and fix.
85

Chapter 4
Functions in Action
Say you want to create a small application that enables someone to schedule a Web conference online. The user might be presented with a text field for the email addresses of all invitees, and two text fields into which she could type a start time and an end time. One of the things that the application would need to do is to check that the dates are valid before saving the reservation and sending out the invitations. Without the use of a function, the code might look something like this:
var fromTime_str:String = “12:00”; var toTime_str:String = “100”; var isFromValid:Boolean = false; var isToValid:Boolean = false;
// Validate the first time
if (fromTime_str.length == 4 && fromTime_str.indexOf(“:”) == 1)
{
// The time has four characters, and the second character is a “:” isFromValid = true;
}
else if (fromTime_str.length == 5 && fromTime_str.indexOf(“:”) == 2)
{
// The time has five characters, and the third character is a “:” isFromValid = true;
}
// Validate the second time
if (toTime_str.length == 4 && toTime_str.indexOf(“:”) == 1)
{
// The time has four characters, and the second character is a “:” isToValid = true;
}
else if (toTime_str.length == 5 && toTime_str.indexOf(“:”) == 2)
{
// The time has five characters, and the third character is a “:” isToValid = true;
}
// Check if both times are valid if (isFromValid && isToValid)
{
trace(“Both fields contain valid times.”);
}
else
{
trace(“There is an error in one of the fields.”);
}
The code goes through the text that comes from two text fields, looking to see if the strings are the right length and the “:” characters are in the right place. You no doubt noticed that the code doing the validation has been duplicated: The code checking the “from” time and the code checking the “to” time is identical except for the different variable names. Placing the validation code within a function helps clean things up:
86

Exploring ActionScript Functions and Scope
function isTimeValid(inputTime_str:String):Boolean
{
var isTimeValid:Boolean = false;
if (inputTime_str.length == 4 && inputTime_str.indexOf(“:”) == 1)
{
// The time has four characters, and the second character is a “:” isTimeValid = true;
}
else if (inputTime_str.length == 5 && inputTime_str.indexOf(“:”) == 2)
{
// The time has five characters, and the third character is a “:” isTimeValid = true;
}
return isTimeValid;
}
var fromTime_str:String = “12:00”; var toTime_str:String = “100”;
if (isTimeValid(fromTime_str) && isTimeValid(toTime_str))
{
trace(“Both fields contain valid times.”);
}
else
{
trace(“There is an error in one of the fields.”);
}
The validation code can now be easily reused. Even better, the code in the function can readily be extended to do something new, such as checking to see if the hour portion is less than 24 and the minute portion is less than 60. Any changes made to this function take effect wherever this function is called.
A few things to note about this new program are that it is shorter, it uses fewer variables, and it groups related logic together. With this one modification, the reusability, organization, and understandability of the code are improved.
An Alternate Syntax
There is another way to define a function in which you create what is sometimes called an anonymous function, and assign that nameless function to a variable of type Function. The alternate syntax looks like this:
var functionName:Function = function(inputValue:DataType):ReturnType
{
// Statements return <value>;
}
87