By Joey Lott
Cover | Table of Contents | Colophon
// Add 6 to the current value of myNum and assign that new value back to myNum. For // example, if myNum was 3, this statement sets it to 9. myNum = myNum + 6;
+=,
-=, *=, and
/= operators are the most prevalent compound
assignment operators. When you use one of these compound assignment
operators, the value on the right side of the assignment operator is
added to, subtracted from, multiplied by, or divided into the value
of the variable on the left, and the new value is assigned to the
same variable. The following are a few examples of equivalent
statements.myNum:myNum = myNum + 6; myNum += 6;
myNum:myNum = myNum - 6; myNum -= 6;
trace(5 == 6); // Displays: false trace(6 == 6); // Displays: true trace(6 == "6"); // Displays: true trace(5 == "6"); // Displays: false
!=) returns false
if two values are equal and true if they are not equal. If necessary,
the operands are converted to the same datatype before the
comparison:trace(5 != 6); // Displays: true trace(6 != 6); // Displays: false trace(6 != "6"); // Displays: false trace(5 != "6"); // Displays: true
trace(6 === 6); // Displays: true trace(6 === "6"); // Displays: false trace(6 !== 6); // Displays: false trace(6 !== "6"); // Displays: true
=) and the equality operator
(==). If you use the assignment operator instead
of the equality operator, you change the variable's
value rather than testing its current value.myVar equals 5 at first, so you
might expect the subsequent if statement to
always evaluate to false, preventing the ? :).if followed by the
test expression whose truthfulness you want to evaluate to determine
which action or actions to execute. The test expression must be in
parentheses, and the statement(s) to be executed should be within
curly braces (the latter is mandatory if there is more than one
statement in the statement block).animalName contains the
word "turtle". This might be used
to check whether the user answered a quiz question correctly (here,
animalName is a variable assumed to contain the
user's answer). Note that the double equals sign
(==) is used to test whether two items are equal.
It should not be confused with the single equals sign
(=), which is used to assign a value to an item.if (animalName == "turtle") {
// This trace( ) statement executes only when animalName is equal to "turtle".
trace("Yay! 'Turtle' is the correct answer.");
}&&), OR
(||), and NOT
(!) operators to create compound
conditional statements.&&), as follows (see Chapter 10 for details on working with dates):// Check if today is April 17th.
now = new Date( );
if (now.getDate() == 17 && now.getMonth( ) == 3) {
trace ("Happy Birthday, Bruce!");
}// Check if today is April 17th.
if ((now.getDate() == 17) && (now.getMonth( ) == 3)) {
trace ("Happy Birthday, Bruce!");
}||) to test whether either condition is true:// Check if it is a weekend.
if ((now.getDay() == 0) || (now.getDay( ) == 6) ) {
trace ("Why are you working on a weekend?");
}// Check to see if the name is not Bruce.
if (!(name == "Bruce")) {
trace ("This application knows only Bruce's birthday.");
}!=):if (name != "Bruce") {
trace ("This application knows only Bruce's birthday.");
}// Check to see if a movie clip is visible. If so, display a message. This condition
// is shorthand for myMovieClip._visible == true.
if (myMovieClip._visible) {
trace("The movie clip is visible.");
}// Check to see if a movie clip is invisible (not visible). If so, display a message. // This condition is shorthand for myMovieClip._visible != true or // myMovieClip._visible == false
for (var i = 0; i < 10; i++) {
// Display the value of i.
trace(i);
}for keyword
for keyword.true or false. The test
expression is evaluated once each time through the loop. Generally,
the test expression compares the index variable to another value,
such as a maximum number of loop iterations. The overall expression
must evaluate to true for the
for statement's body to execute
(contrast this with a do . . . while loop, which
executes at least once, even if the test expression is false). On the
other hand, if the test expression never becomes false,
you'll create an infinite loop, resulting in a
warning that the Flash Player is running slowly (which appears after
15 seconds).// Define a function.
function myIntervalFunction ( ) {
// Output the difference between the current timer value and its value from the
// last time the function was called.
trace(getTimer( ) - lastTime);
lastTime = getTimer( );
}
// Set up an interval that attempts to invoke myIntervalFunction( ) once every
// millisecond.
setInterval(myIntervalFunction, 1);// Set an interval such that someFunction( ) is called approximately once per second. // Assign setInterval( )'s return value to the variable myIntervalID for later use. myIntervalID = setInterval(someFunction, 1000);
clearInterval(myIntervalID);
// Create a simple object using the Object constructor. obj = new Object( ); // Assign a method named myMethod
function functionName ( ) {
// Statements go here.
}
functionName( );
functionName = function ( ) {
// Statements go here.
};// Invoke the writeMessage( ) function, which is declared later in the script.
writeMessage( );
// Declare (define) the function myParamsFunction (param1, param2, param3) {
trace("The average is " + (param1 + param2 + param3)/3);
}arguments
array to handle a variable number of parameters.function myFunction ( ) {
return;
trace("Never called");
}
myFunction( );
// Execution continues here after returning from the myFuction( ) invocation.function checkPassword (password) {
// If password is not "SimonSays", exit the function.
if (password != "SimonSays") {
return;
}
// Otherwise, perform the rest of the actions.
gotoAndStop ("TreasureMap");
}
// This function call uses the wrong password, and so the function exits.
checkPassword("MotherMayI");
// This function uses the correct password, and so the function jumps to the
// TreasureMap frame.
checkPassword("SimonSays");undefined to the caller if no value is specified.
Likewise, if there is no return statement, the
function returns undefined when it terminates. But
any value specified after the return keyword is
returned to script that invoked the function. Usually, the returned
value is stored in a variable for later use:function average (a, b) {
// Return the average of a and b.
return (a + b)/2;
}
var playerScore ;
// Call the average( ) function and store the result in a variable.
playerScore = average(6, 12);
// Use the result in some way.
trace("The player's average score is " + playerScore);trace("The player's average score is " + average(6, 12));average(6, 12);
var keyword to declare
local
variables.var keyword. Parameters are automatically
treated as local variables, so you do not need to include the
var keyword when declaring parameters for a
function.function localVarsFunction (param1, param2) {
var myVar;
myVar = "Local variables are fun.";
}function localVarsFunction (param1, param2) {
var myVar = "Local variables are fun.";
}var keyword are
implicitly scoped to the timeline on which they reside (note that
unlike some languages, ActionScript doesn't require
you to declare a variable before assigning it a value for the first
time). In this case, myVar is a timeline
variable, not a local variable, even though it is declared
within a function:function timelineVarsFunction ( ) {
myVar = "Timeline variables are fun but not usually a good choice in functions.";
}_global object, as follows:_global.companyName = "Person13";
trace ("Welcome to the " + companyName + "web site.");function localVarsFunction ( ) {
var companyName = "Macromedia";
// This displays "Welcome to the Macromedia web site."
trace ("Welcome to the " + companyName + "web site.");
// To access the global variable of the same name, precede it with _global.
// This displays "Welcome to the Person 13 web site."
trace ("Welcome to the " + _global.companyName + "web site.");
}#include directive to add them to your Flash
movies:// Adds all the code within MyActionScriptFile.as to your Flash movie.
#include "MyActionScriptFile.as"#include directive to
incorporate code from external text files
into your Flash movie during compilation from a .fla file to a .swf file. When you export a .swf file, Flash replaces the
#include directive with the contents of the
specified file. The external file must be a text file with valid
ActionScript code in it. By convention the file should be named with
the .as extension, though it is
not absolutely necessary:#include "ASutils.as"
#include directive is not followed
by a semicolon. Adding a semicolon causes an error.// Look for a file named ASutils.as in a subdirectory named myASFiles. #include "myASFiles/ASutils.as"
#include directive (by default, the same
directory as the .fla file) and
is unable to find the file within the Flash System.capabilities object
returns information about the Player and
the computer on which it is running, such as the operating system,
language, and audio capabilities. The System
object also allows you to control some elements of the Player such as
the right-click menu under Windows (Ctrl-click on the Macintosh) and
the Settings dialog box. The Stage object
controls the scaling and alignment of the movie within the Player.System.capabilities.version,
getVersion( ), or $version)
within the Flash Player, as supported by the minimum Player version
you expect to encounter.http://www.macromedia.com/support/flash/ts/documents/browser_support_matrix.htm.System.capabilities object
returns information about the Player and
the computer on which it is running, such as the operating system,
language, and audio capabilities. The System
object also allows you to control some elements of the Player such as
the right-click menu under Windows (Ctrl-click on the Macintosh) and
the Settings dialog box. The Stage object
controls the scaling and alignment of the movie within the Player.System.capabilities.version,
getVersion( ), or $version)
within the Flash Player, as supported by the minimum Player version
you expect to encounter.http://www.macromedia.com/support/flash/ts/documents/browser_support_matrix.htm.http://www.macromedia.com/support/flash/ts/documents/uber_detection.htm
http://www.macromedia.com/support/flash/player/flash_deployment_readme/
http://www.moock.org/webdesign/flash/detection/moockfpi/
$version
or
System.capabilities.os property.$version property string includes the operating
system on which the Player is running. The operating system can be
either "MAC",
"WIN", or
"UNIX".playerParts = _level0.$version.split(" ");
switch (playerParts[0]) {
case "MAC":
gotoAndStop ("WelcomeMac");
break;
case "WIN":
gotoAndStop ("WelcomeWindows");
break;
case "UNIX":
gotoAndStop ("WelcomeUnix");
}System.capabilities.os property, which returns a
string indicating the operating system and version name. Possible
values include "Windows XP",
"Windows 2000",
"Windows NT",
"Windows 98/Me",
"Windows 95", and
"Windows CE". On the Macintosh, the
string includes the version number, such as "MacOS
9.2.1" or "MacOS
10.1.4".os = System.capabilities.os.substr(0, 3);
if (os == "Win") {
// Windows-specific code goes here.
} else if (os == "Mac") {
// Mac-specific code goes here.
} else {
// Must be Unix or Linux
}System.capabilities.language
property.System.capabilities.language
property to determine the language of the computer that is playing
the movie. The property returns a two-letter ISO-639-1 language code
(i.e., "fr" for French). Where
applicable, a two-letter country code is appended, separated from the
language code with a hyphen (i.e.,
"en-US" for U.S. English and
"en-UK" for U.K. English).http://lcweb.loc.gov/standards/iso639-2/englangn.html
http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
language
property:// Example output: en-US trace(System.capabilities.language);
// Create an associative array with language codes
// for the keys and greetings for the values.
greetings = new Array( );
greetings["en"] = "Hello";
greetings["es"] = "Hola";
greetings["fr"] = "Bonjour";
// Extract the first two characters from the language code.
lang = System.capabilities.language.substr(0, 2);
// Use a default language if the language is not in the list.
if (greetings[lang] == undefined) {
lang = "en";
}
// Display the greeting in the appropriate language.
trace(greetings[lang]);// Get the language from the capabilitiesscreenResolutionX
and
screenResolutionY properties of the
System.capabilities object.System.capabilities object to
determine the display settings of the device that is playing the
movie. The screenResolutionX and
screenResolutionY properties return the display
resolution
in pixels.// Example output: // 1024 // 768 trace(System.capabilities.screenResolutionX); trace(System.capabilities.screenResolutionY);
resX = System.capabilities.screenResolutionX;
resY = System.capabilities.screenResolutionY;
// If the resolution is 240 × 320 or less, then load the PocketPC movie version.
// Otherwise, assume the device is a desktop computer and load the regular content.
if ( (resX <= 240) && (resY <= 320) ) {
_root.loadMovie("main_pocketPC.swf");
}
else {
_root.loadMovie("main_desktop.swf");
}resX = System.capabilities.screenResolutionX;
resY = System.capabilities.screenResolutionY;
// Set variables for the width and height of the new browser window.
winW = 200;
winH = 200;
// Determine the x and y values in order to center the window.
winX = (resX / 2) - (winW / 2);
winY = (resY / 2) - (winH / 2);
// Create the code that, when passed to getURL( ), opens the new browser window.
jsCode = "javascript:void(newWin=window.open('http://www.person13.com/'," +
"'newWindow', 'width=" + winW +
", height=" + winH + "," +
"left=" + winX + ",top=" + winY + "'));";
// Call the JavaScript function using Stage.scaleMode
property.Stage.scaleMode = "showAll";
Stage.scaleMode = "noBorder";
Stage.scaleMode = "exactFit";
Stage.scaleMode = "noScale";
scaleMode property's value
does not prevent the user from being able to scale the movie using
the right-click/Ctrl-click menu. However, you can disable those
options in the menu, as shown in Recipe 2.9.Stage.align
property.Stage.align property, as shown in Table 2-1.|
Value
|
Horizontal alignment
|
Vertical alignment
|
|---|---|---|
|
"T"
|
Center
|
Top
|
|
"B"
|
Center
|
Bottom
|
|
"L"
|
Left
|
Center
|
|
"R"
|
Right
|
Center
|
|
"C" or "
"
|
Center
|
Center
|
|
"LT" or
"TL"
|
Left
|
Top
|
|
"RT" or
"TR"
|
Right
|
Top
|
|
"LB" or
"BL"
|
hasAudio and hasMP3
properties
of
the System.capabilities object.System.capabilities.hasAudio property returns
true if the Player has any audio capabilities and
false otherwise. This is extremely important for
playing movies on multiple devices. If a device has no audio support,
you should avoid forcing users to download something they cannot hear
(especially because audio can be quite large):// Load a .swf containing sound only if the Player can play audio.
if (System.capabilities.hasAudio) {
mySoundHolder.loadMovie("sound.swf");
} else {
mySoundHolder.loadMovie("silent.swf");
}System.capabilities.hasMP3 property. MP3
sounds are preferable, if supported, because they offer better
sound-quality-to-file-size ratios than ADCP sounds.// If the Player can play MP3s, load an MP3 using a Sound object. Otherwise, load a // .swf containing ADCP sound into a nested movie clip. if (System.capabilities.hasMP3) { mySound = new Sound(mySoundHolder); mySound.load("sound.mp3", false); } else { mySoundHolder("adcpSound.swf"); }
hasAudio
and hasMP3 property settings are based on the
capabilities of the Player and not of the system on which the Player
is running. The desktop system players (for Windows, Mac OS, and
Linux) always return true for both properties
regardless of whether the system actually has the hardware (i.e.,
soundcard and speakers) to play back sounds. However, players for
other devices may return false if the device does
not support the audio or MP3 features.// Open the Settings dialog box to the Local Storage tab. System.showSettings(1);
Stage.showMenu property to
false.Stage.showMenu = false;
http://www.northcode.com).
SWFKit (http://www.swfkit.com)
offers similar feature enhancements, but we cover only SWF Studio in
detail here.