Macromedia Flash ActionScript - 2.0 User Guide

LEARNING ACTIONSCRIPT™ 2.0 IN FLASH
®
© 2007 Adobe Systems Incorporated. All rights reserved.
Learning ActionScript 2.0 in Adobe® Flash®
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright law. The unauthorized incorporation of such material into your new work could be a violation of the rights of the copyright owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any actual organization.
Adobe®, Flash®, FlashHelp®, Flash® Player, JRun™, Macromedia® and Shockwave® are either registered trademarks or trademarks of Adobe Systems Incorporated
in the United States and/or other countries.
Macintosh® is a trademark of Apple Computer, Inc., registered in the United States and other countries. Windows® is either a registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries. All other trademarks are the property of their respective owners.
Portions of this product contain code licensed from Nellymoser. (www.nellymoser.com).
Sorenson Spark
video compression and decompression technology licensed from Sorenson Media, Inc.
Flash CS3 video is powered by On2 TrueMotion video technology. © 1992-2005 On2 Technologies, Inc.
All Rights Reserved. http://www.on2.com.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA. Notice to U.S. Government End Users. The Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101, consisting of “Commercial Computer Software” and “Commercial Computer Software Documentation,” as such terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software Documentation are being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights as are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright laws of the United States. Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S. Government End Users, Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment Assistance Act of 1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1 through 60-60, 60-250, and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be incorporated by reference.

Contents

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
System requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Updating Flash XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Chapter 1: What’s New in Flash ActionScript . . . . . . . . . . . . . . . . 19
New in ActionScript 2.0 and Flash Player 9.x . . . . . . . . . . . . . . . . . . . . . 19
New in ActionScript 2.0 and
Flash Player 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Changes to security model for locally installed SWF files. . . . . . . . . . 28
Chapter 2: About ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
What is ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
About choosing between ActionScript 1.0 and ActionScript 2.0 . . . 33
Understanding ActionScript and Flash Player . . . . . . . . . . . . . . . . . . . 34
Chapter 3: Data and Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . 35
About data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
About data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
About variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Organizing data in objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
About casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74
Chapter 4: Syntax and Language Fundamentals . . . . . . . . . . . . . 77
About syntax, statements, and expressions . . . . . . . . . . . . . . . . . . . . . . .78
About dot syntax and target paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
About language punctuators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
About constants and keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
About statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103
About arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
About operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
3
Chapter 5: Functions and Methods . . . . . . . . . . . . . . . . . . . . . . . 163
About functions and methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Understanding methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Chapter 6: Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
About object-oriented programming and Flash . . . . . . . . . . . . . . . . . . 188
Writing custom class files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
About working with custom classes in an application . . . . . . . . . . . . . 199
Example: Writing custom classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .223
Example: Using custom class files in Flash . . . . . . . . . . . . . . . . . . . . . .236
Assigning a class to symbols in Flash . . . . . . . . . . . . . . . . . . . . . . . . . . .239
Compiling and exporting classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Understanding classes and scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243
About top-level and built-in classes . . . . . . . . . . . . . . . . . . . . . . . . . . . .246
About working with built-in classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . .256
Chapter 7: Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
About inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .263
About writing subclasses in Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .265
Using polymorphism in an application . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Chapter 8: Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
About interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .275
Creating interfaces as data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Understanding inheritance and interfaces . . . . . . . . . . . . . . . . . . . . . . .282
Example: Using interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .283
Example: Creating a complex interface . . . . . . . . . . . . . . . . . . . . . . . . .285
Chapter 9: Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
About ActionScript and events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .292
Using event handler methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .293
Using event listeners. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .296
Using event listeners with components . . . . . . . . . . . . . . . . . . . . . . . . .298
Using button and movie clip event handlers . . . . . . . . . . . . . . . . . . . . 300
Broadcasting events from component instances. . . . . . . . . . . . . . . . 305
Creating movie clips with button states . . . . . . . . . . . . . . . . . . . . . . . . 305
Event handler scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Scope of the this keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Using the Delegate class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
4Contents
Chapter 10: Working with Movie Clips . . . . . . . . . . . . . . . . . . . . . 313
About controlling movie clips with ActionScript . . . . . . . . . . . . . . . . . .314
Calling multiple methods on a single movie clip . . . . . . . . . . . . . . . . . . 316
Loading and unloading SWF files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Changing movie clip position and appearance . . . . . . . . . . . . . . . . . . .319
Dragging movie clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Creating movie clips at runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
Adding parameters to dynamically created movie clips. . . . . . . . . . . 325
Managing movie clip depths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
About caching and scrolling movie clips with ActionScript . . . . . . . 330
Using movie clips as masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Handling movie clip events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Assigning a class to a movie clip symbol. . . . . . . . . . . . . . . . . . . . . . . . 339
Initializing class properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Chapter 11: Working with Text and Strings . . . . . . . . . . . . . . . . 343
About text fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
About loading text and variables into text fields . . . . . . . . . . . . . . . . . 353
Using fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
About font rendering and anti-alias text . . . . . . . . . . . . . . . . . . . . . . . . 367
About text layout and formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Formatting text with Cascading Style Sheet styles . . . . . . . . . . . . . . 382
Using HTML-formatted text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
Example: Creating scrolling text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .410
About strings and the String class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
Chapter 12: Animation, Filters, and Drawings . . . . . . . . . . . . . . 429
Scripting animation with ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . . . 430
About bitmap caching, scrolling, and performance . . . . . . . . . . . . . 440
About the Tween and TransitionManager classes . . . . . . . . . . . . . . .441
Using filter effects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
Working with filters using ActionScript . . . . . . . . . . . . . . . . . . . . . . . . 463
Manipulating filter effects with code . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
Creating bitmaps with the BitmapData class . . . . . . . . . . . . . . . . . . . . 493
About blending modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
About operation order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Drawing with ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Understanding scaling and slice guides . . . . . . . . . . . . . . . . . . . . . . . . .514
Contents 5
Chapter 13: Creating Interaction with ActionScript . . . . . . . . . . 519
About events and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Controlling SWF file playback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Creating interactivity and visual effects . . . . . . . . . . . . . . . . . . . . . . . . 524
Creating runtime data bindings using ActionScript . . . . . . . . . . . . . . .537
Deconstructing a sample script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .546
Chapter 14: Working with Images, Sound, and Video . . . . . . . 549
About loading and working with external media . . . . . . . . . . . . . . . . 550
Loading external SWF and image files. . . . . . . . . . . . . . . . . . . . . . . . . . 551
About loading and using external MP3 files . . . . . . . . . . . . . . . . . . . . 555
Assigning linkage to assets in the library . . . . . . . . . . . . . . . . . . . . . . . 559
About using FLV video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
About creating progress animations for media files. . . . . . . . . . . . . . 580
Chapter 15: Working with External Data . . . . . . . . . . . . . . . . . . 589
Sending and loading variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
Using HTTP to connect to server-side scripts . . . . . . . . . . . . . . . . . . 594
About file uploading and downloading . . . . . . . . . . . . . . . . . . . . . . . . . 600
About XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
Sending messages to and from Flash Player . . . . . . . . . . . . . . . . . . . . 617
About the External API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
Chapter 16: Understanding Security . . . . . . . . . . . . . . . . . . . . . . 631
About compatibility with previous Flash Player security models . . . 631
About local file security and Flash Player . . . . . . . . . . . . . . . . . . . . . . . .633
Restricting networking APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .648
About domains, cross-domain security, and SWF files . . . . . . . . . . 650
Server-side policy files for permitting access to data . . . . . . . . . . . . .657
HTTP to HTTPS protocol access between SWF files . . . . . . . . . . . .662
Chapter 17: Best Practices and Coding Conventions for
ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
Naming conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .666
Using comments in your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
ActionScript coding conventions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
ActionScript and Flash Player optimization . . . . . . . . . . . . . . . . . . . . 695
Formatting ActionScript syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
6Contents
Appendix A: Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
Appendix B: Deprecated Flash 4 operators . . . . . . . . . . . . . . . . 713
Appendix C: Keyboard Keys and Key Code Values . . . . . . . . . . 715
Appendix D: Writing Scripts for Earlier Versions of Flash Player . . 721
About targeting earlier versions of Flash Player . . . . . . . . . . . . . . . . . . 721
Using Flash to create content for Flash Player 4 . . . . . . . . . . . . . . . . 722
Appendix E: Object-Oriented Programming with ActionScript 1.0. 725
About ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726
Creating a custom object in ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . 728
Assigning methods to a custom object in ActionScript 1.0. . . . . . . . 729
Defining event handler methods in ActionScript 1.0 . . . . . . . . . . . . . 730
Creating inheritance in ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . 732
Adding getter/setter properties to objects in ActionScript 1.0. . . . . 734
Using Function object properties in ActionScript 1.0 . . . . . . . . . . . . . 735
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .737
Contents 7
8Contents

Introduction

Adobe Flash CS3 Professional is the professional standard authoring tool for producing high­impact web experiences. ActionScript is the language you use to add interactivity to Flash applications, whether your applications are simple animated SWF files or more complex rich Internet applications. You don’t have to use ActionScript to use Flash, but if you want to provide basic or complex user interactivity, work with objects other than those built into Flash (such as buttons and movie clips), or otherwise turn a SWF file into a more robust user experience, you’ll probably want to use ActionScript.
For more information, see the following topics:
Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Updating Flash XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
System requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Intended audience

This manual assumes that you have already installed Flash and know how to use the user interface.You should know how to place objects on the Stage and manipulate them in the Flash authoring environment. If you have used a scripting language before, ActionScript will seem familiar. But if you’re new to programming, ActionScript basics are easy to learn. You can start with simple commands and build more complexity as you progress. You can add a lot of interactivity to your files without having to learn (or write) a lot of code.
9

System requirements

ActionScript 2.0 does not have any system requirements in addition to Flash.
Flash CS3 Professional introduces ActionScript 3.0. Flash Player 9 and ActionScript 3.0 are the default publishing settings for Flash. This manual provides information on how to use ActionScript 2.0 with Flash. You must change the publishing settings for your Flash files to Flash Player 9 and ActionScript 2.0. If you do not change the default settings, explanations and code samples in the documentation might not work correctly. If you develop applications for earlier versions of Flash Player, see Appendix D, “Writing Scripts for Earlier Versions of
Flash Player,” on page 721.

Updating Flash XML files

It is important that you always have the latest Flash XML files installed. Adobe sometimes introduces features in dot releases (minor releases) of Flash Player. When such a release is available, you should update your version of Flash to get the latest XML files. Otherwise, the Flash compiler might generate errors if you use new properties or methods that were unavailable in the version of Flash Player that came with your Flash installation.
For example, Flash Player 7 (7.0.19.0) contained a new method for the System object,
System.security.loadPolicyFile. To access this method, you must use the Player
Updater installer to update all the Flash players that are installed with Flash. Otherwise, the Flash compiler displays errors.
Remember that you can install a Player Updater that is one or more major versions ahead of your version of Flash. By doing this, you will get the XML files that you need but shouldn’t have any compiler errors when you publish to older versions of Flash Player. Sometimes new methods or properties are available to older versions, and having the latest XML files minimizes the compiler errors you get when you try to access older methods or properties.
10 Introduction

About the documentation

This manual provides an overview of ActionScript syntax and information on how to use ActionScript when working with different types of objects. For details on the syntax and usage of every language element, see the ActionScript 2.0 Language Reference.
For more information, see the following topics:
“Learning ActionScript 2.0 book overview” on page 11
“About the sample files” on page 14
“Terms used in this document” on page 13
“Copy and paste code” on page 13

Learning ActionScript 2.0 book overview

The following list summarizes the contents of this manual:
Chapter 1, “What’s New in Flash ActionScript,” describes features that are new in
ActionScript, changes to the compiler and debugger, and the new programming model for the ActionScript 2.0 language.
Chapter 2, “About ActionScript,” outlines what the ActionScript language is and details
how to choose between which version of ActionScript to use.
Chapter 3, “Data and Data Types,” describes the terminology and basic concepts about
data, data types, and variables. You use these concepts throughout the manual.
Chapter 4, “Syntax and Language Fundamentals,” describes the terminology and basic
concepts of the ActionScript language. You use these concepts throughout the manual.
Chapter 5, “Functions and Methods,” describes how to write different kinds of functions
and methods and how to use them in your application.
Chapter 6, “Classes,” describes how to create custom classes and objects in ActionScript.
This chapter also lists the built-in classes in ActionScript and provides a brief overview of how you use them to access powerful features in ActionScript.
Chapter 7, “Inheritance,” describes inheritance in the ActionScript language and describes
how to extend built-in or custom classes.
Chapter 8, “Interfaces,” describes how to create and work with interfaces in ActionScript.
Chapter 9, “Handling Events,” describes a few different ways to handle events: event
handler methods, event listeners, and button and movie clip event handlers.
Chapter 10, “Working with Movie Clips,” describes movie clips and the ActionScript you
can use to control them.
About the documentation 11
Chapter 11, “Working with Text and Strings,” describes the different ways you can
control text and strings in Flash and includes information on text formatting and advanced anti-aliasing.
Chapter 12, “Animation, Filters, and Drawings,” describes how to create code-based
animation and images, add filters to objects, and draw using ActionScript.
Chapter 13, “Creating Interaction with ActionScript,” describes some simple ways in
which you can create more interactive applications, including controlling when SWF files play, creating custom pointers, and creating sound controls.
Chapter 14, “Working with Images, Sound, and Video,” describes how to import external
media files, such as bitmap images, MP3 files, Flash Video (FLV) files, and other SWF files, in your Flash applications. This chapter also provides an overview of how to work with video in your applications, and how to create progress bar loading animations.
Chapter 15, “Working with External Data,” describes how to process data from external
sources using server- or client-side scripts in your applications. This chapter describes how to integrate data with your applications.
Chapter 16, “Understanding Security,” explains security in Flash Player, as it pertains to
working with SWF files locally on your hard disk. This chapter also explains cross-domain security issues, and how to load data from servers, or across domains.
Chapter 17, “Best Practices and Coding Conventions for ActionScript 2.0,” explains the
best practices for using Flash and writing ActionScript. This chapter also lists standardized coding conventions, such as naming variables, and other conventions.
Appendix A, “Error Messages,” lists the error messages that the Flash compiler can
generate.
Appendix B, “Deprecated Flash 4 operators,” lists all the deprecated Flash 4 operators and
their associativity.
Appendix C, “Keyboard Keys and Key Code Values,” lists all the keys on a standard
keyboard and the corresponding ASCII key code values that are used to identify the keys in ActionScript.
Appendix D, “Writing Scripts for Earlier Versions of Flash Player,” provides guidelines to
help you write scripts that are syntactically correct for the player version you are targeting.
Appendix E, “Object-Oriented Programming with ActionScript 1.0,” provides
information on using the ActionScript 1.0 object model to write scripts.
This manual explains how to use the ActionScript language. For information on the language elements themselves, see the ActionScript 2.0 Language Reference.
12 Introduction

Typographical conventions

This manual uses the following typographical conventions:
Code font indicates ActionScript code.
Bold code font, typically within a procedure, indicates code that you need to modify or
add to code you have already added to your FLA file. In some case, it might be used to highlight code to look at.
Boldface text indicates data you need to type into the user interface, such as a filename or
instance name.
Italic text indicates a new term defined in the text that follows. In a file path, it might
indicate a value that should be replaced (for example, with a directory name on your own hard disk).

Terms used in this document

The following terms are used in this manual:
You refers to the developer who is writing a script or application.
The user refers to the person who is running your scripts and applications.
Compile time is the time at which you publish, export, test, or debug your document.
Runtime is the time at which your script is running in Flash Player.

Copy and paste code

When you paste ActionScript from the Help panel into your FLA or ActionScript file, you have to be careful about special characters. Special characters include special quotation marks (also called curly quotation marks or smart quotation marks). These characters are not interpreted by the ActionScript editor, so your code throws an error if you try to compile it in Flash.
You can determine that your quotation mark characters are special characters if they do not color-code correctly. That is, if all your strings do not change in color in the code editor, you need to replace the special characters with regular straight quotation mark characters. If you type a single or double quotation mark character directly into the ActionScript editor, you always type a straight quotation mark character. The compiler (when you test or publish a SWF file) throws an error and lets you know if there are the wrong kind (special quotation marks or curly quotation marks) of characters in your code.
NOTE
You might also encounter special quotation marks if you paste ActionScript from other locations, such as a web page or a Microsoft Word document.
About the documentation 13
Be cautious of proper line breaks when you copy and paste code. If you paste your code from some locations, the line of code might break in an improper location. Make sure that the color coding of your syntax is correct in the ActionScript editor if you think line breaks might be a problem. You might want to compare your code in the Actions panel to that in the Help panel to see if it matches. Try turning on Word Wrap in the ActionScript editor to help solve surplus line breaks in your code (select View > Word Wrap in the Script window, or Word Wrap from the Actions panel pop-up menu.)

Additional resources

In addition to this manual about ActionScript, there are manuals on other Flash topics, such as components and Adobe Flash Lite. You can access each manual in the Help panel (Help > Flash Help), by viewing the default Table of Contents. Click the Clear button to see each manual that’s available; for more information, see “Where to find documentation on other
subjects” on page 17.
For more information about other available resources, see the following topics:
“About the sample files” on page 14
“Where to find PDF files or printed documentation” on page 15
“About LiveDocs” on page 15
“Additional online resources” on page 16
“Where to find documentation on other subjects” on page 17

About the sample files

There are numerous ActionScript-based sample files available that install with Flash. These sample files show you how code works in a FLA file; this is often a useful learning tool. The chapters in this manual often reference these files, but we recommend that you also check out the sample files folder on your hard disk.
The sample files include application FLA files that use common Flash functionality installed with Flash. These applications were designed to introduce new Flash developers to the capabilities of Flash applications, as well as show advanced developers how Flash features work in context.
14 Introduction
For samples of ActionScript-focused sample source files, see the Flash Samples page at
www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and
navigate to the ActionScript2.0 folder to access the samples. For components-focused sample files, navigate to the ComponentsAS2 folder.

Where to find PDF files or printed documentation

If you prefer to read documentation in printed format, the PDF versions of each Help manual are available for downloading. Go to www.adobe.com/support/documentation/ and select the product you’re interested in. You can view or download the PDF or link to the LiveDocs version of the manual.
Often, you can also purchase printed documentation. For updated information, go to the
Documentation support site.

About LiveDocs

You can access documentation at the LiveDocs website, in addition to accessing it from the Help panel. The LiveDocs website contains all of the Flash Help pages and might contain comments that clarify, update, or correct parts of the documentation. Click View Comments on LiveDocs at the bottom of a page in the Help panel to display the equivalent page on the LiveDocs website. Go to http://livedocs.macromedia.com to see a list of all of the available documentation in the LiveDocs format.
Technical writers monitor the LiveDocs website. One of the advantages of LiveDocs is seeing comments that clarify the documentation or correct any errata or issues that arise after a software release. LiveDocs is not the place to make help requests, such as asking questions about your code that doesn’t work, comment on problems with software or installation, or ask how to create something with Flash. It is the correct place to provide feedback about the documentation (for example, you notice a sentence or paragraph that could be clarified).
When you click the button to add a comment on LiveDocs, there are several points about the kinds of comments that are acceptable on the system. Please read these guidelines closely, or your comment might be removed from the website.
If you have a question about Flash, please ask it on the Adobe web forums: www.adobe.com/
support/forums/. The web forums are the best place to ask questions, because there are many
Adobe employees, Team Adobe volunteers, Adobe user group managers and members, and even technical writers who monitor these forums.
Additional resources 15
Engineers do not monitor the LiveDocs system but do monitor the Flash wish list. If you think you have found a bug in the software, or you would like to request an enhancement to Flash, please fill out the wishform at www.adobe.com/go/wish. If you report your bug or enhancement request on LiveDocs, it will not be officially added to the bug database. You must use the wishform instead, if you want an engineer to see your bug or request.
Remember to be careful about special characters and line breaks when you paste from the web, including LiveDocs. Adobe has made every effort to remove all special characters from code samples, but if you have problems pasting code, see “Copy and paste code” on page 13.

Additional online resources

There are several resources online that offer a wealth of instruction, help, and guidance to help you learn Flash. Check the following websites often for updates:
The Adobe Developer Center website (www.adobe.com/devnet) is updated regularly with
the latest information on Flash, plus advice from expert users, advanced topics, examples, tips, tutorials (including multipart tutorials), and other updates. Check the website often for the latest news on Flash and how to get the most out of the program.
The Adobe Flash Support Center (www.adobe.com/support/flash) provides TechNotes,
documentation updates, and links to additional resources in the Flash community.
The Adobe Weblogs website (http://weblogs.macromedia.com) provides a list of both
Adobe employee and community weblogs (also known as blogs).
The Adobe web forums (http://www.adobe.com/support/forums/) provides numerous
forums for asking specific questions about Flash, your applications, or the ActionScript language. The forums are monitored by Team Adobe volunteers and often visited by Adobe employees as well. If you’re not sure where to go, or how to solve a problem, a Flash forum is a good place to start.
The Adobe Community website (www.adobe.com/community) regularly hosts a series of live
presentations on a variety of topics by Adobe employees or community members. Check the website often for updates.
16 Introduction

Where to find documentation on other subjects

The following manuals offer additional information on subjects commonly associated with ActionScript 2.0:
For information about the elements that compose the ActionScript language, see the
ActionScript 2.0 Language Reference.
For information about working in the Flash authoring environment, see How to Use Help.
For information about working with components, see Using ActionScript 2.0 Components.
Additional resources 17
18 Introduction
CHAPTER 1

What’s New in Flash ActionScript

Adobe Flash CS3 Professional provides several enhancements that make it easy for you to write robust scripts using the ActionScript language. The new features, which are discussed in this chapter, include new language elements (see “Additions to the ActionScript language in
Flash Player 8” on page 22), improved editing tools (see “ActionScript editing changes” on page 27), changes to the security model, and other ActionScript-related improvements to
the authoring tool.
For more information, see the following topics:
New in ActionScript 2.0 and Flash Player 9.x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
New in ActionScript 2.0 and Flash Player 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Changes to security model for locally installed SWF files. . . . . . . . . . . . . . . . . . . . . . 28
New in ActionScript 2.0 and Flash Player
9.x
1
Flash Player 9.x allows a user to switch the Flash Player into and out of fullscreen mode. The following items support this new feature:
Stage.displayState property
Stage.onFullScreen event handler
allowFullScreen parameter in the object and embed HTML tags
For more information, see ActionScript 2.0 Language Reference.
Flash Player 9.x also introduces a new FileReference event, event can be invoked after a server receives a successful upload. For more information on this new item, see ActionScript 2.0 Language Reference.
onUploadCompleteData. This
19

New in ActionScript 2.0 and Flash Player 8

The ActionScript language has grown and developed since its introduction several years ago. With each new release of Flash, additional keywords, objects, methods, and other language elements were added to ActionScript. There are also ActionScript-related improvements to the Flash 8 authoring environments. Flash Basic 8 and Flash Professional 8 introduced several new language elements for expressive features, such as filters and blending modes, and application development, such as JavaScript integration (ExternalInterface) and file input and output (FileReference and FileReferenceList).
This section provides an overview of the ActionScript language elements and classes that are new or changed in Flash 8 and ActionScript-related improvements to the authoring tool. For a list of specific additions to ActionScript 2.0, see “Additions to the ActionScript language in
Flash Player 8” on page 22. To use any of the new language elements in your scripts, you must
target Flash Player 8 when you publish your documents.
The following features were added to both Flash Basic 8 and Flash Professional 8 (unless noted otherwise):
ActionScript editor enhancements let you show hidden characters in your scripts. For
more information, see “Display hidden characters” in Using Flash.
Debug options are now available in the Script window, as well as the Actions panel, for
ActionScript files.
The Configuration directory that includes XML files and Class files is reorganized. See
“Configuration folders installed with Flash” in Using Flash for details.
You can set a preference to reload modified script files when working on an application,
which helps you avoid working with older versions of script files, and overwriting newer script files. For more information, see “Set ActionScript preferences” in Using Flash.
The Script window feature is available in Flash. That means you can now create an
ActionScript file in either program.
Script Assist (similar to Normal Mode in earlier editions of Flash) helps you code without
needing to understand syntax. For more information on Script Assist, see “About Script Assist mode” in Using Flash.
You can load new kinds of image files at runtime, which include progressive JPEG images,
and non-animated GIF and PNG files. If you load an animated file, the first frame of the animation appears.
You can assign linkage identifiers to bitmap and sound files stored in the Library, which
means that you can attach images to the Stage or work with these assets in shared libraries.
20 What’s New in Flash ActionScript
Bitmap caching lets you improve the performance of your applications at runtime by
caching a bitmap representation of your instances. You can use ActionScript code to access this property. For more information, see “About bitmap caching, scrolling, and
performance” on page 440.
9-slice scaling lets you scale movie clip instances without widening the strokes that outline
the movie clip. You can use ActionScript code to access this feature in Flash. For more information, see “Working with 9-slice scaling in ActionScript” on page 516. For information about accessing 9-slice scaling in the authoring tool, see Using Flash.
You can now add metadata information to your FLA files in the Document Properties
dialog box. You can add a name and description to your FLA file using the dialog box to help increase online search visibility.
The Strings panel is improved to include multiline support in the String field and a
language XML file. For more information, see “panel” on page 413.
A new garbage collector is built into Flash Player, which uses an incremental collector to
improve performance.
The workflow for creating accessible applications is improved. Flash Player 8 no longer
requires developers to add all objects to the tab index for content to be read correctly by a screen reader. For more information on tab index, see
property)
(TextField.tabIndex property)
Flash Player has improved local file security, for additional safety when running SWF files
, tabIndex (MovieClip.tabIndex property), and tabIndex
in the ActionScript 2.0 Language Reference.
tabIndex (Button.tabIndex
on your hard disk. For information on local file security, see “About local file security and
Flash Player” on page 633.
Using ActionScript code, you can use the Drawing API to control the line style of strokes
that you draw. For information on new line styles, see “Using line styles” on page 506.
Using ActionScript code, you can use the Drawing API to create more complex gradients
that you fill shapes with. For information on gradient fills, see “Using complex gradient
fills” on page 505.
You can use ActionScript code to apply many filters to objects on the Stage (such as movie
clip instances). For information on filters and ActionScript, see “Working with filters
using ActionScript” on page 463.
You can use the FileReference and FileReferenceList API to upload files to a server. For
more information, see “About file uploading and downloading” on page 600.
You can use ActionScript code to access new and advanced ways of applying and
manipulating colors. For more information, see “Setting color values” on page 530 and
ColorTransform (flash.geom.ColorTransform) in the ActionScript 2.0 Language
Reference.
New in ActionScript 2.0 and Flash Player 8 21
Numerous improvements are made to text handling, including new options, properties,
and parameters in the TextField and TextFormat classes. For more information, see
TextField and TextFormat in the ActionScript 2.0 Language Reference.
You can use ActionScript code to access advanced anti-aliasing features. For more
information, see “About font rendering and anti-alias text” on page 367.
You can delete ASO files when you test your application. Select Control > Delete ASO
files or Control > Delete ASO files and Test Movie in the authoring tool. For information, see “Using ASO files” on page 242.
For a list of specific classes, language elements, methods, and properties added to ActionScript
2.0 in Flash 8, see “Set ActionScript preferences” in Using Flash.

Additions to the ActionScript language in Flash Player 8

The following classes and language elements are new additions or newly supported in Flash Player 8.
The following classes were added to ActionScript 2.0 in Flash 8:
The BevelFilter class (in flash.filters package) lets you add bevel effects to objects.
The BitmapData class (in flash.display package) lets you create and manipulate arbitrarily
sized transparent or opaque bitmap images.
The BitmapFilter class (in flash.display package) is a base class for filter effects.
The BlurFilter class lets you apply blurs to objects in Flash.
The ColorMatrixFilter class (in flash.filters package) lets you apply transformations to
ARGB colors and alpha values.
The ColorTransform class (in the flash.geom package) lets you adjust color values in
movie clips. The Color class is deprecated in favor of this class.
The ConvolutionFilter class (in the flash.filters package) lets you apply matrix
convolution filter effects.
The DisplacementMapFilter class (in the flash.filters package) lets you use pixel values
from a BitmapData object to perform displacement on an object.
The DropShadowFilter class (in the flash.filters package) lets you add drop shadows
to objects.
The ExternalInterface class (in the flash.external package) lets you communicate by using
ActionScript with the Flash Player container (the system holding the Flash application, such as a browser with JavaScript, or the desktop application).
22 What’s New in Flash ActionScript
The FileReference class (in the flash.net package) lets you upload and download files
between the user’s computer and a server.
The FileReferenceList class (in the flash.net package) lets you select one or more files
to upload.
The GlowFilter class (in the flash.filters package) lets you add glow effects to objects.
The GradientBevelFilter class (in the flash.filters package) lets you add gradient bevels
to objects.
TheGradientGlowFilter class (in the flash.filters package) lets you add gradient glow
effects to objects.
The IME class (in the System class) lets you manipulate the operating system’s input
method editor (IME) within Flash Player.
The Locale class (in the mx.lang package) lets you control how multilanguage text appears
in a SWF file.
The Matrix class (in the flash.geom package) represents a transformation matrix that
determines how to map points from one coordinate space to another.
The Point class (in the flash.geom package) represents a location in a two-dimensional
coordinate system (x represents the horizontal axis, and y represents the vertical axis).
The Rectangle class (in the flash.geom package) lets you create and modify Rectangle
objects.
The TextRenderer class (in the flash.text package) provides functionality for advanced
anti-aliased embedded fonts.
The Transform class (in the flash.geom package) collects data about color transformations
and coordinates manipulations that you apply to a MovieClip instance.
NOTE
Official support is added for the AsBroadcaster class in Flash 8.
New language elements, methods, and functions added to existing classes in ActionScript include:
The showRedrawRegions global function provides the ability for the debugger player to
outline the regions of the screen that are being redrawn (that is, dirty regions that are being updated). The function has the player show what was redrawn, but does not let you control redraw regions.
The blendMode property in the Button class, which sets the blending mode for the
button instance.
The cacheAsBitmap property in the Button class, which lets you cache the object as an
internal bitmap representation of the instance.
New in ActionScript 2.0 and Flash Player 8 23
The filters property in the Button class, which is an indexed array that contains each
filter object associated with the button.
The scale9Grid property in the Button class, which is the rectangular region that defines
nine scaling regions for the instance.
The hasIME property in the System.capabilities class, which indicates if the system has an
IME installed.
The getUTCYear property in the Date class, which returns the year of this date, according
to universal time.
The isAccessible() method in the Key class returns a Boolean value that indicates
whether the last key pressed may be accessed by other SWF files, depending on security restrictions.
The onHTTPStatus event handler of the LoadVars class returns the status code that’s
returned from the server (for example, the value 404 for page not found). For more information, see
HTTPStatus (LoadVars.onHTTPStatus handler) in the ActionScript
2.0 Language Reference.
The attachBitmap() method of the MovieClip class, which attaches a bitmap image to a
movie clip. For information, see
BitmapData (flash.display.BitmapData) in the
ActionScript 2.0 Language Reference.
The beginBitmapFill() method of the MovieClip class, which fills a movie clip with a
bitmap image.
The spreadMethod, interpolationMethod, and focalPointRatio parameters of the
beginGradientFill() method in the MovieClip class. This method fills a drawing area
with a bitmap image, and the bitmap can be repeated or tiled to fill the area.
The blendMode property of the MovieClip class, which lets you set the blending mode for
the instance.
The cacheAsBitmap property of the MovieClip class, which lets you cache the object as
an internal bitmap representation of the instance.
The filters property of the MovieClip class, which is an indexed array that contains
each filter object that’s currently associated with the instance.
The getRect() method of the MovieClip class, which returns properties that are the
minimum and maximum coordinate values of the specified instance.
The lineGradientStyle() method of the MovieClip class, which specifies a gradient
line style that Flash uses when drawing a path.
The pixelHinting, noScale, capsStyle, jointStyle, and miterLimit parameters of
the
lineStyle() method in the MovieClip class. These parameters specify kinds of line
styles you can use when drawing lines.
24 What’s New in Flash ActionScript
The opaqueBackground property of the MovieClip class, which sets the color of the
movie clip’s opaque (not transparent) background to the color that the RGB hexadecimal value specifies.
The scale9Grid property of the MovieClip class, which is the rectangular region that
defines nine scaling regions for the instance.
The scrollRect property of the MovieClip class, which lets you quickly scroll movie clip
content and have a window viewing larger content.
The transform property of the MovieClip class, which lets you make settings regarding a
movie clip’s matrix, color transform, and pixel bounds. For more information, see
Transform (flash.geom.Transform) in ActionScript 2.0 Language Reference.
The status parameter of the MovieClipLoader.onLoadComplete event handler returns
the status code that’s returned from the server (for example, the value 404 for page not found). For more information, see
event listener)
The onLoadError event handler of the MovieClipLoader class is invoked when a file
loaded with
The secure parameter of the SharedObject.getLocal() method determines whether
in ActionScript 2.0 Language Reference.
MovieClipLoader.loadClip() fails to load.
onLoadComplete (MovieClipLoader.onComplete
access to this shared object is restricted to SWF files delivered over an HTTPS connection. For more information, see
getLocal (SharedObject.getlocal method) in
ActionScript 2.0 Language Reference.
The sandboxType property of the System.security class indicates the type of security
sandbox in which the calling SWF file is operating. For more information, see
sandboxType (security.sandboxType property) in ActionScript 2.0 Language
Reference.
The antiAliasType property in the TextField class, which sets the type of advanced anti-
aliasing that you use for the TextField instance.
The filters property in the TextField class, which is an indexed array that contains each
filter object that’s currently associated with the TextField instance.
The gridFitType property in the TextField class, which sets the type of grid fitting that
you use for the instance. For information on grid fitting and TextField.gridFitType, see
gridFitType (TextField.gridFitType property) in ActionScript 2.0 Language
Reference.
The sharpness property in the TextField class, which sets the sharpness of the glyph
edges for the TextField instance. You must set the
antiAliasType() method to advanced
if you use this property.
New in ActionScript 2.0 and Flash Player 8 25
The thickness property in the TextField class, which sets the thickness of the glyph edges
in the TextField instance. You must set the
antiAliasType() method to advanced if you
use this property.
The justify value for the align property of the TextFormat class, which lets you justify
a specified paragraph.
The indent property of the TextFormat class, which lets you use negative values.
The kerning property in the TextFormat class, which lets you turn kerning on or off for
the TextFormat object.
The leading property of the TextFormat class, which lets you use negative leading, so the
space between lines is less than the text height. This lets you put lines of text close together in your applications.
The letterSpacing property in the TextFormat class, which lets you specify the amount
of space that is uniformly distributed between characters.
The _alpha property in the Video class, which is the specified amount of transparency for
the video object.
The _height property in the Video class, which indicates the height of the video instance.
The _name property in the Video class, which indicates the instance name of the video.
The _parent property in the Video class, which indicates the movie clip instance or
object that contains the video instance.
The _rotation property in the Video class, which lets you set the amount of rotation of
the video instance in degrees.
The _visible property in the Video class, which lets you set the visibility of a
video instance.
The _width property in the Video class, which lets you set the width of the
video instance.
The _x property in the Video class, which lets you set the x coordinate of the
video instance.
The _xmouse property in the Video class, which lets you set the x coordinate of the mouse
pointer position.
The _xscale property in the Video class, which lets you set the horizontal scale
percentage of the video instance.
The _y property in the Video class, which lets you set the y coordinate of the
video instance.
The _ymouse property in the Video class, which lets you set the y coordinate of the mouse
pointer position.
26 What’s New in Flash ActionScript
The _yscale property in the Video class, which lets you set the vertical scale percentage
of the video instance.
The onHTTPStatus event handler in the XML class returns the status code that’s returned
from the server (for example, the value 404 for page not found). For more information, see
onHTTPStatus (XML.onHTTPStatus handler) in ActionScript 2.0 Language
Reference.
The localName property of the XMLNode class, which returns the full name of the XML
node object (including both the prefix and the local name).
The namespaceURI property of the XMLNode class, which reads the URI of the
namespace to which the XML node’s prefix resolves. For more information, see
namespaceURI (XMLNode.namespaceURI property) in ActionScript 2.0 Language
Reference.
The prefix property of the XMLNode class, which reads the prefix of the node name.
The getNamespaceForPrefix() method of the XMLNode class, which returns the
namespace URI associated with the specified prefix for the node.
The getPrefixForNamespace method of the XMLNode class, which returns the prefix
associated with a specified namespace URI for the node.

About deprecated language elements

Some language elements are deprecated in Flash Player 8. For a list of deprecated language elements, and alternatives to use in Flash Player 8, see the following sections in ActionScript
2.0 Language Reference:
Deprecated Class summary
Deprecated Function summary
Deprecated Property summary
Deprecated Operator summary

ActionScript editing changes

The ActionScript editor in the Actions panel and Script window has been updated in several ways to make it more robust and easier to use than earlier versions of the tool. The changes are summarized in this section.
View hidden characters You can now use the Options pop-up menu in the Script pane,
Debugger panel, and Output panel to view or hide hidden characters when you’re writing script files in the Actions panel or Script window. For information on this feature, see Using Flash.
New in ActionScript 2.0 and Flash Player 8 27
Script assist added to Actions panel In previous versions of Flash, you could work in the
Actions panel either in normal mode, in which you filled in options and parameters to create code, or in expert mode, in which you added commands directly into the Script pane. These options were not available in Flash MX 2004 or Flash MX Professional 2004. However, in Flash Basic 8 and Flash Professional 8, you can work in Script Assist mode, which is similar to (and more robust than) normal mode. For information and a tutorial on Script Assist, see Using Flash.
Reload modified files You can reload modified script files when working on an application.
A warning message appears, prompting you to reload the modified script files associated with the application you’re working on. This feature is particularly beneficial to teams working on applications at the same time, in that it helps you avoid working with outdated scripts, or overwriting newer versions of a script. If a script file was moved or deleted, a warning message appears and prompts you to save the files as necessary. For more information, see “Set ActionScript preferences” in Using Flash.

Changes to security model for locally installed SWF files

Flash Player 9.x introduces support for a new HTML tag, allowNetworking. For more information, see the Security chapter in Programming ActionScript 3.0.
Flash Player 8 introduced a new, improved security model in which Flash applications and SWF files on a local computer can communicate with the Internet and the local file system, rather than run from a remote web server. When you develop a Flash application, you must indicate whether a SWF file is allowed to communicate with a network or with a local file system.
NOTE
In this description, a local SWF file is a SWF file that is locally installed on a user’s computer, not served from a website, and does not include projector (EXE) files.
In previous versions of Flash Player, local SWF files could interact with other SWF files and load data from any remote or local computer without configuring security settings. In Flash Player 8 and later, a SWF file cannot make connections to the local file system and the network (such as the Internet) in the same application without making a security setting. This is for your safety, so a SWF file cannot read files on your hard disk and then send the contents of those files across the Internet.
28 What’s New in Flash ActionScript
This security restriction affects all locally deployed content, whether it’s legacy content (a FLA file created in an earlier version of Flash) or created in Flash 8 and later. Using the Flash MX 2004 or earlier authoring tool, you could test a Flash application that runs locally and also accesses the Internet. In Flash Player 8 and later, this application now prompts the user for permission to communicate with the Internet.
When you test a file on your hard disk, there are several steps to determine whether the file is a local trusted (safe) document or a potentially untrusted (unsafe) document. If you create the file in the Flash authoring environment (for example, when you select Control > Test Movie), your file is trusted because it is in the test environment.
In Flash Player 7 and earlier, local SWF files had permissions to access both the local file system and the network. In Flash Player 8 and later, local SWF files can have three levels of permission:
Access the local file system only (the default level). The local SWF file can read from the
local file system and universal naming convention (UNC) network paths and cannot communicate with the Internet.
Access the network only. The local SWF file can access the network only (such as the
Internet) and not the local file system where the SWF file is installed.
Access to both the local file system and the network. The local SWF file can read from the
local file system where the file is installed, read from and write to any server that grants it permission, and can cross-script other SWF files on either the network or the local file system that grant it permission.
For more details about each level of permission, see “About local file security and Flash Player”
on page 633.
There are also minor changes to System.security.allowDomain and improvements to System.security.allowInsecureDomain. For more information on local file security, see
Chapter 16, “Understanding Security.”
Changes to security model for locally installed SWF files 29
30 What’s New in Flash ActionScript
CHAPTER 2

About ActionScript

The object-oriented programming (OOP) features in ActionScript 2.0 are based on the ECMAScript 4 Draft Proposal currently in development by ECMA TC39-TG1 (see
www.mozilla.org/js/language/es4/index.html). Because the ECMA-4 proposal is not yet a
standard, and because it is still changing, ActionScript 2.0 is loosely based on this specification.
ActionScript 2.0 supports all the standard elements of the ActionScript language; it lets you write scripts that more closely adhere to standards used in other object-oriented languages, such as Java. ActionScript 2.0 should be of interest primarily to intermediate or advanced Flash developers who are building applications that require the implementation of classes and subclasses. ActionScript 2.0 also lets you declare the object type of a variable when you create it (see “About assigning data types and strict data typing” on page 45) and provides significantly improved compiler errors (see Appendix A, “Error Messages,” on page 707).
Key facts about ActionScript 2.0 include the following points:
Scripts that use ActionScript 2.0 to define classes or interfaces must be stored as external
script files, with a single class defined in each script; that is, classes and interfaces cannot be defined in the Actions panel.
You can import individual class files implicitly (by storing them in a location specified by
global or document-specific search paths and then using them in a script) or explicitly (by using the directory) by using wildcards.
Applications developed with ActionScript 2.0 are supported by Flash Player 6 and later.
CAUTION
import command); you can import packages (collections of class files in a
The default publish setting for new files created in Flash CS3 is ActionScript 3.0. If you plan to modify an existing FLA file with ActionScript 1.0 or ActionScript 2.0 to use ActionScript 2.0 syntax, ensure that the FLA file specifies ActionScript 2.0 in its publish settings. If it does not, your file will compile incorrectly, although Flash will not necessarily generate compiler errors.
2
31
For more information on using ActionScript 2.0 to write object-oriented programs in Flash, see Chapter 6, “Classes,” on page 187.
Although Adobe recommends that you use ActionScript 3.0, you can continue to use ActionScript 1.0 and ActionScript 2.0 syntax.

What is ActionScript

The main features of ActionScript 2.0 include the following:
Familiar object-oriented programming (OOP) model The primary feature of
ActionScript 2.0 is a familiar model for creating object-oriented programs. ActionScript 2.0 implements several object-oriented concepts and keywords such as class, interface, and packages that will be familiar to you if you’ve programmed with Java.
The OOP model provided by ActionScript 2.0 is a “syntactic formalization” of the prototype chaining method used in previous versions of Flash to create objects and establish inheritance. With ActionScript 2.0, you can create custom classes and extend Flash’s built-in classes.
Strict data typing ActionScript 2.0 also lets you explicitly specify data types for variables,
function parameters, and function return types. For example, the following code declares a variable named
var userName:String = "";
Compiler warnings and errors
typing) enable the authoring tool and compiler to provide compiler warnings and error messages that help you find bugs in your applications faster than was previously possible in Flash.
When you use ActionScript 2.0, make sure that the publish settings for the FLA file specify ActionScript 2.0 (the default for Flash CS3 is ActionScript 3.0). Additionally, if you open an older FLA file that uses ActionScript 1.0 and begin rewriting it in ActionScript 2.0, change the publish settings of the FLA file to ActionScript 2.0. If you don’t, your FLA file will not compile correctly, and errors won’t be generated.
userName of type String (a built-in ActionScript data type, or class).
The previous two features (OOP model and strict data
32 About ActionScript
About choosing between ActionScript
1.0 and ActionScript 2.0
When you start a new document or application in Flash, you must decide how to organize its associated files. You might use classes in some projects, such as when you are building applications or complex FLA files, but not all documents use classes. For example, many short examples in the documentation do not use classes. Using classes to store functionality is not the easiest or best solution for small applications or simple FLA files. It is often more efficient to put ActionScript inside the document. In this case, try to put all your code on the Timeline on as few frames as possible, and avoid placing code on or in instances (such as buttons or movie clips) in a FLA file.
When you build a small project, it is often more work and effort to use classes or external code files to organize ActionScript instead of adding ActionScript within the FLA file. Sometimes it is easier to keep all the ActionScript code within the FLA file, rather than placing it within a class that you import. This does not mean that you should necessarily use ActionScript 1.0. You might decide to put your code inside the FLA file by using ActionScript 2.0 with its strict data typing and its new methods and properties. ActionScript 2.0 also offers a syntax that follows standards in other programming languages. This makes the language easier and more valuable to learn. For example, you will feel familiar with ActionScript if you have encountered another language that’s based on the same structure and syntax standards. Or, you can apply this knowledge to other languages you learn in the future. ActionScript 2.0 lets you use an object-oriented approach to developing applications by using an additional set of language elements, which can be advantageous to your application development.
In some cases, you cannot choose which version of ActionScript to use. If you are building a SWF file that targets an old version of Flash Player, such as a mobile device application, you must use ActionScript 1.0, which is compatible with Flash Player for a number of devices.
Remember, regardless of the version of ActionScript, you should follow good practices. Many of these practices, such as remaining consistent with case sensitivity, using code completion, enhancing readability, avoiding keywords for instance names, and keeping a consistent naming convention, apply to both versions.
If you plan to update your application in future versions of Flash, or make it larger and more complex, you should use ActionScript 2.0 and classes, to make it easier to update and modify your application.

About choosing between ActionScript 1.0 and ActionScript 2.0 33

Understanding ActionScript and Flash Player

If you compile a SWF file that contains ActionScript 2.0 with publish settings set to Flash Player 6 and ActionScript 1.0, your code functions as long as it does not use ActionScript 2.0 classes. No case sensitivity is involved with the code, only Flash Player. Therefore, if you compile your SWF file with Publish Settings set to Flash Player 7 and later and ActionScript
1.0, Flash enforces case sensitivity.
Data type annotations (strict data types) are enforced at compile time for Flash Player 7 and later when you have publish settings set to ActionScript 2.0.
ActionScript 2.0 compiles to ActionScript 1.0 bytecode when you publish your applications, so you can target Flash Player 6 and later while working with ActionScript 2.0.
34 About ActionScript
CHAPTER 3

Data and Data Types

This chapter is the first of several chapters that outline and demonstrate some fundamental concepts of ActionScript. You’ll practice some basic coding techniques to learn how to create complex applications. In this chapter, you’ll also learn about how to work with data in a FLA file, and what kinds of data you can work with. In the next chapter, Chapter 4, “Syntax and
Language Fundamentals,” you’ll discover how to use ActionScript syntax and form
statements. Following this, Chapter 5, “Functions and Methods” demonstrates how to use functions and methods in the ActionScript language.
For more information about data and data types, see the following sections:
About data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
About data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
About variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50
Organizing data in objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
About casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

About data

Data refers to the numbers, strings, and other information that you can manipulate within Flash. Using data is usually essential when you create applications or websites. You also use data when you create advanced graphics and script-generated animation, and you might have to manipulate values that you use to drive your effects.
You c an d efi n e da ta i n variables within Flash, or you can load data from external files or sites using XML, web services, built-in ActionScript classes, and so on. You can store data in a database, and then represent that information in several ways in a SWF file. This can include displaying the information in text fields or components, or displaying images in movie clip instances.
3
35
Some of the most common kinds of data include strings (a sequence of characters, such as names and passages of text), numbers, objects (such as movie clips), Boolean values (
false), and so on. In this chapter, you’ll also learn about the data types in Flash and how to
true and
use them.
For information on types of data, see “About data types” on page 36. For information on variables, see “About variables” on page 50.

About data types

A data type describes a piece of data and the kinds of operations that you can perform on it. You store data in a variable. You use data types when creating variables, object instances, and function definitions to assign the type of data you’re working with. You use many different data types when you write ActionScript.
ActionScript 2.0 defines several commonly used data types. Data types describe the kind of value that a variable or ActionScript element can contain. A variable that is assigned a data type can only hold a value within that data type’s set of values. For information on variables, see “About variables” on page 50.
ActionScript has numerous basic data types that you will probably use frequently in your applications. See the table in “About primitive and complex data types” on page 37 for more information.
ActionScript also has core classes, such as Array and Date, that are considered complex or reference data types. For more info on complex and reference data types, see “About primitive
and complex data types” on page 37. In addition, all data types and classes are fully defined in
ActionScript 2.0 Language Reference.
You can also create custom classes for your applications. Any class that you define using the class declaration is also considered a data type. For more information on core and other built­in classes, see “About top-level and built-in classes” on page 246. For more information on creating custom classes, see Chapter 6, “Classes,” on page 187.
In ActionScript 2.0, you can assign data types to variables when you declare them. The data types you assign can be any of the core types or can represent a custom class that you created. For more information, see “About assigning data types and strict data typing” on page 45.
When you debug scripts, you might need to determine the data type of an expression or variable to understand why it is behaving a certain way. You can do this with the and
typeof operators (see “About determining data type” on page 49).
instanceof
36 Data and Data Types
You can convert one data type to another at runtime using one of the following conversion functions:
Array(), Boolean(), Number(), Object(), String().
For a sample of the datatypes.fla file, which shows you how to use data types in an application, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and navigate to the ActionScript2.0/DataTypes folder to access the sample.

About primitive and complex data types

You can divide all the different data type values into two main categories: primitive or complex.
A primitive value (or primitive data type) is a value that ActionScript stores at the lowest level of abstraction, which means that operations on the primitive data types are generally faster and more efficient than operations carried out on complex data types. The following data types all define a set of one or more primitive values: Boolean, null, Number, String, and undefined.
A complex value (or complex data type) is a value that is not a primitive value and that references the primitive values. Often, these are called reference data types. Complex values belong to the Object data type or a data type that is based on the Object data type. Data types that define sets of complex values include Array, Date, Error, Function, and XML. For more information on these complex data types, see their entries in the ActionScript 2.0 Language Reference.
Variables that contain primitive data types behave differently in certain situations than those containing complex types. For more information, see “Using variables in a project”
on page 69.
ActionScript has the following basic data types that you can use in your applications:
Data type Description
Boolean Primitive. The Boolean data type consists of two values: true and false.
No other values are valid for variables of this type. The default value of Boolean variable that has been declared but not initialized is more information, see “Boolean data type” on page 38.
MovieClip Complex. The MovieClip data type lets you control movie clip symbols
using the methods of the MovieClip class. For more information, see
“MovieClip data type” on page 40.
About data types 37
false. For
Data type Description
null Primitive. The null data type contains the value null. This value means
no value—that is, a lack of data. You can assign the null value in a variety of situations to indicate that a property or variable does not have a value assigned to it. The null data type is the default data type for all classes that define complex data types. An exception to this rule is the Object class, which defaults to
“null data type” on page 41
Number Primitive. This data type can represent integers, unsigned integers, and
floating point numbers. To store a floating point number, you should include a decimal point in the number. Without the decimal point, the number is stored as an integer. The Number data type can store values from
Number.MAX_VALUE (very high) to Number.MIN_VALUE (very low). For
more information, see ActionScript 2.0 Language Reference and
“Number data type” on page 42.
Object Complex. The Object data type is defined by the Object class. The
Object class serves as the base class for all class definitions in ActionScript, and it lets you arrange objects inside each other (nested objects). For more information, see “Object data type” on page 42.
String Primitive. The String data type represents a sequence of 16-bit
characters that might include letters, numbers, and punctuation marks. Strings are stored as Unicode characters, using the UTF-16 format. An operation on a String value returns a new instance of the string. For more information, see “String data type” on page 43.
undefined Primitive. The undefined data type contains one value:
the default value for instances of the Object class. You can only assign a value of information, see “undefined data type” on page 44
Void Complex. The Void data type contains only one value: void. You use this
data type to designate functions that don’t return a value. Void is a complex data type that references the primitive Void data type. For more information, see “Void data type” on page 44.
undefined to variables that belong to the Object class. For more
undefined. For more information, see
.
undefined. This is
.
For a sample of the datatypes.fla file, see the Flash Samples page at www.adobe.com/go/
learn_fl_samples. Download and decompress the Samples zip file and navigate to the
ActionScript2.0/DataTypes folder to access the sample.
Boolean data type
A Boolean value is one that is either true or false. ActionScript also converts the values
true and false to 1 and 0 when appropriate. Boolean values are most often used with logical
operators in ActionScript statements that make comparisons to control the flow of a script.
38 Data and Data Types
The following example loads a text file into a SWF file, and displays a message in the Output panel if the text file does not load correctly, or the parameters if it does load successfully. See the comments in the code example for more details.
var my_lv:LoadVars = new LoadVars(); //success is a Boolean value my_lv.onLoad = function(success:Boolean) {
//if success is true, trace monthNames if (success) {
trace(my_lv.monthNames); //if success is false, trace a message } else {
trace("unable to load text file"); }
}; my_lv.load("http://www.helpexamples.com/flash/params.txt");
The following example checks that users enter values into two TextInput component instances. Two Boolean variables are created, and if both variables evaluate to
true, a welcome message is assigned to the titleMessage
userNameEntered and isPasswordCorrect,
String variable.
// Add two TextInput components, a Label, and a Button component on the
Stage.
// Strict data type the three component instances var userName_ti:mx.controls.TextInput; var password_ti:mx.controls.TextInput; var submit_button:mx.controls.Button; var welcome_lbl:mx.controls.Label;
//Hide the label welcome_lbl.visible = false;
// Create a listener object, which is used with the Button component. // When the Button is clicked, checks for a user name and password. var btnListener:Object = new Object(); btnListener.click = function(evt:Object) {
// Checks that the user enters at least one character in the TextInput // instances and returns a Boolean true/false. var userNameEntered:Boolean = (userName_ti.text.length > 0); var isPasswordCorrect:Boolean = (password_ti.text == "vertigo"); if (userNameEntered && isPasswordCorrect) {
var titleMessage:String = "Welcome " + userName_ti.text + "!";
welcome_lbl.text = titleMessage;
//display the label
welcome_lbl.visible = true; }
}; submit_button.addEventListener("click", btnListener);
About data types 39
For more information, see “Using functions in Flash” on page 176 and “About logical
operators” on page 155.
MovieClip data type
Movie clips are symbols that can play animation in a Flash application. They are the only data type that refers to a graphic element. The MovieClip data type lets you control movie clip symbols using the methods of the MovieClip class.
You do not use a constructor to call the methods of the MovieClip class. You can create a movie clip instance on the Stage or create an instance dynamically. Then you simply call the methods of the MovieClip class using the dot (
Working with movie clips on the Stage The following example calls the startDrag() and getURL() methods for different movie clip instances that are on the Stage:
my_mc.startDrag(true); parent_mc.getURL("http://www.adobe.com/support/" + product);
The second example returns the width of a movie clip called my_mc on the Stage. The targeted instance must be a movie clip, and the returned value must be a numeric value.
function getMCWidth(target_mc:MovieClip):Number {
return target_mc._width;
} trace(getMCWidth(my_mc));
Creating movie clips dynamically
Using ActionScript to create movie clips dynamically is useful when you want to avoid manually creating movie clips on the Stage or attaching them from the library. For example, you might create an image gallery with a large number of thumbnail images that you want to organize on the Stage. Using
MovieClip.createEmptyMovieClip() lets you create an application entirely using
ActionScript.
To dynamically create a movie clip, use the following example:
// Creates a movie clip to hold the container. this.createEmptyMovieClip("image_mc", 9); // Loads an image into image_mc. image_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");
.) operator.
MovieClip.createEmptyMovieClip(), as shown in
40 Data and Data Types
The second example creates a movie clip called square_mc that uses the Drawing API to draw a rectangle. Event handlers and the
startDrag() and stopDrag() methods of the MovieClip
class are added to make the rectangle draggable.
this.createEmptyMovieClip("square_mc", 1); square_mc.lineStyle(1, 0x000000, 100); square_mc.beginFill(0xFF0000, 100); square_mc.moveTo(100, 100); square_mc.lineTo(200, 100); square_mc.lineTo(200, 200); square_mc.lineTo(100, 200); square_mc.lineTo(100, 100); square_mc.endFill(); square_mc.onPress = function() {
this.startDrag(); }; square_mc.onRelease = function() {
this.stopDrag(); };
For more information, see Chapter 10, “Working with Movie Clips,” on page 313 and the MovieClip entry in the ActionScript 2.0 Language Reference.
null data type
The null data type has only one value, null. This value means no value—that is, a lack of data. You can assign the does not yet have a value assigned to it. For example, you can assign the following situations:
To indicate that a variable exists but has not yet received a value
To indicate that a variable exists but no longer contains a value
As the return value of a function, to indicate that no value was available to be returned by
the function
As a parameter to a function, to indicate that a parameter is being omitted
Several methods and functions return demonstrates how you can use
if (Selection.getFocus() == null) {
trace("no selection"); }
null value in a variety of situations to indicate that a property or variable
null value in the
null if no value has been set. The following example
null to test if form fields currently have form focus:
About data types 41
Number data type
The Number data type is a double-precision floating-point number. The minimum value of a number object is approximately 5e-324. The maximum is approximately 1.79E+308.
You can manipulate numbers using the arithmetic operators addition ( multiplication (
*), division (/), modulo (%), increment (++), and decrement (--). For more
+), subtraction (-),
information, see “Using numeric operators” on page 149.
You can also use methods of the built-in Math and Number classes to manipulate numbers. For more information on the methods and properties of these classes, see the Math and Number entries in ActionScript 2.0 Language Reference.
The following example uses the
sqrt() (square root) method of the Math class to return the
square root of the number 100:
Math.sqrt(100);
The following example traces a random integer between 10 and 17 (inclusive):
var bottles:Number = 0; bottles = 10 + Math.floor(Math.random() * 7); trace("There are " + bottles + " bottles");
The following example finds the percent of the intro_mc movie clip that is loaded and represents it as an integer:
var percentLoaded:Number = Math.round((intro_mc.getBytesLoaded() /
intro_mc.getBytesTotal()) * 100);
Object data type
An object is a collection of properties. A property is an attribute that describes the object. For example, the transparency of an object (such as a movie clip) is an attribute that describes its appearance. Therefore, value. The value of a property can be any Flash data type—even the Object data type. This lets you arrange objects inside each other, or nest them.
To specify objects and their properties, you use the dot ( following code,
employee:
employee.weeklyStats.hoursWorked
The ActionScript MovieClip object has methods that let you control movie clip symbol instances on the Stage. This example uses the
mcInstanceName.play(); mc2InstanceName.nextFrame();
_alpha (transparency) is a property. Each property has a name and a
.) operator. For example, in the
hoursWorked is a property of weeklyStats, which is a property of
play() and nextFrame() methods:
42 Data and Data Types
You can also create custom objects to organize information in your Flash application. To add interactivity to an application with ActionScript, you need many pieces of information: for example, you might need a user’s name, age, and phone number; the speed of a ball; the names of items in a shopping cart; the number of frames loaded; or the key that the user pressed last. Creating custom objects lets you organize this information into groups, simplify your scripting, and reuse your scripts.
The following ActionScript code shows an example of using custom objects to organize information. It creates a new object called
phone, which are String and Numeric data types.
var user:Object = new Object(); user.name = "Irving"; user.age = 32; user.phone = "555-1234";
user and creates three properties, name, age, and
For more information, see “Example: Writing custom classes” on page 223.
String data type
A string is a sequence of characters such as letters, numbers, and punctuation marks. You enter strings in an ActionScript statement by enclosing them in single (') or double (") quotation marks.
A common way that you use the string type is to assign a string to a variable. For example, in the following statement,
var favoriteBand_str:String = "L7";
You can use the addition (+) operator to concatenate, or join, two strings. ActionScript treats spaces at the beginning or end of a string as a literal part of the string. The following expression includes a space after the comma:
var greeting_str:String = "Welcome, " + firstName;
To include a quotation mark in a string, precede it with a backslash character (\). This is called escaping a character. There are other characters that cannot be represented in ActionScript except by special escape sequences. The following table lists all the ActionScript escape characters:
"L7" is a string assigned to the variable favoriteBand_str:
Escape sequence Character
\b
\f
\n
\r
Backspace character (ASCII 8)
Form-feed character (ASCII 12)
Line-feed character (ASCII 10)
Carriage return character (ASCII 13)
About data types 43
Escape sequence Character
\t
\"
\'
\\
\000 - \377
\x00 - \xFF
\u0000 - \uFFFF
Tab character (ASCII 9)
Double quotation mark
Single quotation mark
Backslash
A byte specified in octal
A byte specified in hexadecimal
A 16-bit Unicode character specified in hexadecimal
Strings in ActionScript are immutable, just as they are in Java. Any operation that modifies a string returns a new string.
The String class is a built-in ActionScript class. For information on the methods and properties of the String class, see the String entry in the ActionScript 2.0 Language Reference.
undefined data type
The undefined data type has one value, undefined, and is automatically assigned to a variable to which a value hasn’t been assigned, either by your code or user interaction.
The value variable or property. You use the undefined data type to check if a variable is set or defined. This data type lets you write code that executes only when the application is running, as shown in the following example:
if (init == undefined) {
}
If your application has multiple frames, the code does not execute a second time because the
init variable is no longer undefined.
undefined is automatically assigned; unlike null, you don’t assign undefined to a
trace("initializing app");
init = true;
Void data type
The Void data type has one value, void, and is used in a function definition to indicate that the function does not return a value, as shown in the following example:
//Creates a function with a return type Void function displayFromURL(url:String):Void {}
44 Data and Data Types

About assigning data types and strict data typing

You use variables in Flash to hold values in your code. You can explicitly declare the object type of a variable when you create the variable, which is called strict data typing.
If you do not explicitly define an item as holding either a number, a string, or another data type, at runtime Flash Player will try to determine the data type of an item when it is assigned. If you assign a value to a variable, as shown in the following example, Flash Player evaluates at runtime the element on the right side of the operator and determines that it is of the Number data type:
var x = 3;
Because x was not declared using strict data typing, the compiler cannot determine the type; to the compiler, the variable
on page 46.) A later assignment might change the type of
x = "hello" changes the type of x to String.
ActionScript always converts primitive data types (such as Boolean, Number, String, null, or undefined) automatically when an expression requires the conversion and the variables aren’t strictly typed.
Strict data typing offers several benefits at compile time. Declaring data types (strict data typing) can help prevent or diagnose errors in your code at compile time. To declare a variable using strict data typing, use the following format:
var variableName:datatype;
NOTE
Strict data typing is sometimes called strong typing a variable.
x can have a value of any type. (See “Assigning a data type”
x; for example, the statement
Because data type mismatches trigger compiler errors, strict data typing helps you find bugs in your code at compile time and prevents you from assigning the wrong type of data to an existing variable. During authoring, strict data typing activates code hinting in the ActionScript editor (but you should still use instance name suffixes for visual elements).
Using strict data typing helps ensure that you don’t inadvertently assign an incorrect type of value to a variable. Flash checks for typing mismatch errors at compile time, and displays an error message if you use the wrong type of value. Therefore, using strict typing also helps to ensure that you do not attempt to access properties or methods that are not part of an object’s type. Strict data typing means the ActionScript editor automatically shows code hints for objects.
About data types 45
For more information on creating variables, see “About variables” on page 50. For information on naming variables, see “About naming variables” on page 55. For more information on assigning data types, and the types you can assign, see “Assigning a data type”
on page 46.
For a sample of the datatypes.fla file, which shows you how to use data types in an application, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and navigate to the ActionScript2.0/DataTypes folder to access the sample.
Assigning a data type
You need to assign data types whenever you define a variable, whether you declare a variable using the variable to use within a which means you follow the variable name with a colon and then the data type:
var my_mc:MovieClip;
There are many possibilities for data types, ranging from the native data types such as Number, String, Boolean, or built-in classes that are included in Flash Player 8, such as BitmapData, FileReference, or even custom classes that you or other developers have written. The most common types of data types you might need to specify are the built-in data types such as Number, String, Boolean, Array, or Object, which are shown in the following code examples.
To assign a specific data type to an item, specify its type using the colon syntax, as shown in the following example:
// Strict typing of variable or object var myNum:Number = 7; var birthday:Date = new Date();
var keyword, create a function argument, set function return type, or define a
for or for..in loop. To assign a data type, you use post-colon syntax,
var keyword and post-
// Strict typing of parameters function welcome(firstName:String, age:Number) { }
// Strict typing of parameter and return value function square(myNum:Number):Number { var squared:Number = myNum * myNum; return squared; }
46 Data and Data Types
You can declare the data type of objects based on built-in classes (Button, Date, and so on) as well as classes and interfaces that you create. In the following example, if you have a file named Student.as in which you define the Student class, you can specify that objects you create are of type Student:
var myStudent:Student = new Student();
For this example, suppose you type the following code:
// in the Student.as class file class Student { public var status:Boolean; // property of Student objects }
// in the FLA file var studentMaryLago:Student = new Student(); studentMaryLago.status = "enrolled"; /* Type mismatch in assignment
statement: found String where Boolean is required. */
When Flash compiles this script, a type mismatch error is generated because the SWF file expects a Boolean value.
If you write a function that doesn’t have a return type, you can specify a return type of Void for that function. Or if you create a shortcut to a function, you can assign a data type of Function to the new variable. To specify that objects are of type Function or Void, see the following example:
function sayHello(name_str:String):Void {
trace("Hello, " + name_str); } sayHello("world"); // Hello, world var greeting:Function = sayHello; greeting("Augustus"); // Hello, Augustus
Another advantage of strict data typing is that Flash automatically shows code hints for built­in objects when they are strictly typed. For more information, see “About assigning data types
and strict data typing” on page 45.
Files published using ActionScript 1.0 do not respect strict data typing assignments at compile time, so assigning the wrong type of value to a variable that you have strictly typed doesn’t generate a compiler error.
var myNum:String = "abc"; myNum = 12; /* No error in ActionScript 1.0, but type mismatch error in ActionScript 2.0
*/
About data types 47
The reason for this is that when you publish a file for ActionScript 1.0, Flash interprets a statement such as
var myNum:String = "abc" as slash syntax rather than as strict typing.
(ActionScript 2.0 doesn’t support slash syntax.) This behavior can result in an object that is assigned to a variable of the wrong type, causing the compiler to let illegal method calls and undefined property references pass through unreported.
Files published using ActionScript 2.0 can optionally use data typing. Therefore, if you implement strict data typing in your code, make sure you set your publish settings to ActionScript 2.0. You can specify the publish settings and define which version of ActionScript you want to publish your files as by modifying the publish settings from the main menu (File > Publish Settings) or by clicking the Settings button in the Property inspector (make sure no instances are selected). To use a specific version of ActionScript or the Flash Player, select the Flash tab in the Publish Settings dialog box, and make a selection from the ActionScript version pop-up menu.
For information on type checking, see “About type checking” on page 48.

About type checking

Type checking refers to verifying that the type of a variable and an expression are compatible. Therefore, Flash checks that the type you specify for a variable matches the value(s) that you assign to it. For more information on strict data types and assigning data types, see “Ab ou t
assigning data types and strict data typing” on page 45 and “Assigning a data type” on page 46.
Type checking can occur at either compile time or runtime. If you use strict data typing, type checking occurs at compile time. Because ActionScript is a dynamically typed language, ActionScript can also type checking at runtime.
For example, the following code does not specify the data type of the parameter runtime, you use the parameter to hold a value of type Number and then a value of type
String. The dynamicTest() function then uses the typeof operator to test whether the
parameter is of type String or Number.
function dynamicTest(xParam) {
if (typeof(xParam) == "string") {
var myStr:String = xParam; trace("String: " + myStr);
} else if (typeof(xParam) == "number") {
var myNum:Number = xParam; trace("Number: " + myNum);
} } dynamicTest(100); dynamicTest("one hundred");
xParam. At
48 Data and Data Types
You do not need to explicitly add data type information in your ActionScript. The ActionScript compiler lets you use properties and invoke methods that do not exist at compile time. This lets you create properties or assign dynamically methods at runtime.
An example of the flexibility afforded by dynamic type checking involves the use of properties and methods that are not known at compile time. Because the code is less restrictive, it can lead to benefits in some coding situations. For example, the following code creates a function named
runtimeTest() that invokes a method and returns a property, neither of which is
known to the compiler. The code will not generate a compile-time error, but if the property or method is not accessible at runtime, then a runtime error will occur.
function runtimeTest(myParam) {
myParam.someMethod();
return myParam.someProperty; }

About determining data type

While testing and debugging your programs, you might discover problems that seem to be related to the data types of different items. Or if you use variables that are not explicitly associated with a data type, you might find it useful to know the data type of a given variable. Using ActionScript, you can determine an item’s data type. You can use the to return information about data.
Use the
typeof operator to get the data types, but remember that typeof does not return
information about the class to which an instance belongs.
The following example shows how you can use the
typeof operator to return the kind of
object that you trace:
// Create a new instance of LoadVars class. var my_lv:LoadVars = new LoadVars();
typeof operator
/* typeof operator doesn't specify class, only specifies that my_lv is an
object */ var typeResult:String = typeof(my_lv); trace(typeResult); // object
In this example, you create a new String variable named myName, and then convert it into a Number data type:
var myName:String = new String("17"); trace(myName instanceof String); // true var myNumber:Number = new Number(myName); trace(myNumber instanceof Number); // true
About data types 49
For more information about these operators, see typeof operator and instanceof
operator
in the ActionScript 2.0 Language Reference. For more information on testing and debugging, see Using Flash. For more information on inheritance and interfaces, see Chapter
7, “Inheritance,” on page 263. For more information on classes, see Chapter 6, “Classes,” on page 187.

About variables

A variable is a container that holds information. The following ActionScript shows what a variable looks like in ActionScript:
var myVariable:Number = 10;
This variable holds a numerical value. The use of :Number in the previous code assigns the type of value that variable holds, called data typing. For more information on data typing, see
“About assigning data types and strict data typing” on page 45 and “Assigning a data type” on page 46.
The container (represented by the variable name) is always the same throughout your ActionScript, but the contents (the value) can change. You can change the value of a variable in a script as many times as you want. When you change the value of a variable while the SWF file plays, you can record and save information about what the user has done, record values that change as the SWF file plays, or evaluate whether a condition is might need the variable to continually update while the SWF file plays, such as when a player’s score changes in a Flash game. Variables are essential when you create and handle user interaction in a SWF file.
It’s a good idea to assign a value to a variable the first time you declare the variable. Assigning an initial value is called initializing the variable, and it’s often done on Frame 1 of the Timeline or from within a class that loads when the SWF file begins to play. There are different kinds of variables, which are affected by scope. For more information on different kinds of variables and scope, see “About variables and scope” on page 60.
TIP
Initializing a variable helps you track and compare the variable’s value as the SWF file plays.
true or false. You
NOTE
Flash Player 7 and later evaluate uninitialized variables differently than Flash Player 6 and earlier. If you have written scripts for Flash Player 6 and plan to write or port scripts for Flash Player 7 or later, you should be understand these differences to avoid unexpected behavior.
50 Data and Data Types
Variables can hold different types of data; for more information, see “About data types”
on page 36. The type of data that a variable contains affects how the variable’s value changes
when you assign that value in a script.
Typical types of information that you can store in a variable include a URL (String type), a user’s name (String type), the result of a mathematical operation (Number type), the number of times an event occurred (Number type), or whether a user has clicked a particular button (Boolean type). Each SWF file and object instance (such as a movie clip) has a set of variables, with each variable having a value independent of variables in other SWF files or movie clips.
To view the value of a variable, use the
trace() statement to send the value to the Output
panel. Then, the value displays in the Output panel when you test the SWF file in the test environment. For example,
hoursWorked to the Output panel in the test environment. You can also check and set the
trace(hoursWorked) sends the value of the variable
variable values in the Debugger in the test environment.
For more information on variables, see the following topics:
“About declaring variables” on page 51
“About assigning values” on page 52
“About naming variables” on page 55
“Using variables in an application” on page 56
“About variables and scope” on page 60
“About default values” on page 52
“About operators and variables” on page 54
“About loading variables” on page 64
“Using variables in a project” on page 69

About declaring variables

You can declare variables on a frame in the timeline, directly on an object, or within an external class file.
Define variables using the declare a variable called
var firstName:String;
When you declare a variable, you assign a data type to the variable. In this case, you assign the String data type to the
“About assigning data types and strict data typing” on page 45.
var keyword and follow the variable naming conventions. You can
firstName, as shown in the following example:
firstName variable. For more information on assigning data types, see
About variables 51

About default values

A default value is the value that a variable contains before you set its value. You initialize a variable when you set its value for the first time. If you declare a variable, but do not set its value, that variable is uninitialized. The value of an uninitialized variable defaults to the value
undefined. For more information on creating and using variables, see “About variables”
on page 50.

About assigning values

You c an d efi n e a value as the current contents of a variable. The value can be a strings, numbers, arrays, objects, XML, dates, or even custom classes that you create. Remember, you declare a variable in Flash using the assign a data type to the variable. You can also assign a value to a variable, as long as the value matches the data type you assign to the variable.
The following example shows how you might create a variable called
var catName:String;
After you declare the variable, you can assign a value to it. You might follow the previous line of ActionScript with this line:
catName = "Pirate Eye";
NOTE
Because Pirate Eye is a string, the value needs to be enclosed in straight quotes (quotation marks).
var keyword. When you declare the variable, you also
catName:
This example assigns the value of Pirate Eye to the catName variable. When you declare the variable, you can also assign a value to it instead of assigning it afterwards (as in the previous examples). You could set the
catName variable when you declare it, as shown in the
following example:
var catName:String = "Pirate Eye";
If you want to display the value of the catName variable in the test environment, you can use the
trace() statement. This statement sends the value to the Output panel. You can trace the
value of the
catName variable and see that the actual value doesn’t include the quotation
marks by using the following ActionScript:
var catName:String = "Pirate Eye"; trace(catName); // Pirate Eye
52 Data and Data Types
Remember that the value you assign must match the data type that you assign to it (in this case, String). If you later try to assign a number to the
, you will see the following error in the Output panel when you test the SWF file:
10
Type mismatch in assignment statement: found Number where String is
required.
catName variable, such as catName =
This error tells you that you attempted to set the wrong data type to a specified variable.
When you assign a numeric value to a variable, the quotation marks aren’t necessary, as shown in the following code:
var numWrinkles:Number = 55;
If you want to change the value of numWrinkles later in your code, you can assign a new value using the following ActionScript:
numWrinkles = 60;
When you reassign a value to an existing variable, you don’t need to use the var keyword or define the variable’s data type (in this case,
If the value is numeric or Boolean (
:Number).
true or false), the value doesn’t use straight quotes
(quotation marks). Examples of numeric and Boolean values are shown in the following snippet:
var age:Number = 38; var married:Boolean = true; var hasChildren:Boolean = false;
In the previous example, the variable age contains an integer (nondecimal) value, although you could also use a decimal or floating-point value such as 38.4. Boolean variables (such as
married or hasChildren) have only two possible values, true or false.
If you want to create an array and assign values to it, the format is slightly different, as shown in the following code:
var childrenArr:Array = new Array("Pylon", "Smithers", "Gil");
There is an alternative (shorthand) syntax for creating an array using array access operators, which use the bracket (
var childrenArr:Array = ["Pylon", "Smithers", "Gil"];
[]) punctuators. You can rewrite the previous example as follows:
For more information on creating arrays and the array access operators, see “Abou t ar r ay s”
on page 125 and “About using dot syntax to target an instance” on page 82.
About variables 53
Similarly, you can create a new object called myObj. You can use either of the following ways to create a new object. The first (and longer) way to code an array is as follows:
var myObj:Object = new Object(); myObj.firstName = "Steve"; myObj.age = 50; myObj.childrenArr = new Array("Mike", "Robbie", "Chip");
The second, shorthand way you can code the myObj array is as follows:
var myObj:Object = {firstName:"Steve", age:50, childrenArr:["Mike",
"Robbie", "Chip"]};
As you see in this example, using the shorthand method can save a lot of typing and time, especially when you define instances of objects. It is important to be familiar with this alternate syntax because you will encounter it if you work in teams or when you work with third-party ActionScript code that you find, for example, on the Internet or in books.
NOTE
Not all variables need to be explicitly defined. Some variables are created by Flash automatically for you. For example, to find the dimensions of the Stage, you could use the values of the following two predefined values: Stage.width and Stage.height.

About operators and variables

You might wonder about the mathematical symbols in your code. These symbols are called operators in ActionScript. Operators calculate a new value from one or more values, and you use an operator to assign a value to a variable in your code. You use the equality ( to assign a value to a variable:
var username:String = "Gus";
Another example is the addition (+) operator, which you use to add two or more numeric values to produce a new value. If you use the + operator on two or more string values, the strings will be concatenated. The values that operators manipulate are called operands.
When you assign a value, you use an operator to define a value to a variable. For example, the following script uses the assignment operator to assign a value of 7 to the variable
numChildren:
var numChildren:Number = 7;
If you want to change the value of the numChildren variable, use the following code:
numChildren = 8;
NOTE
You don’t need to use var because the variable has previously been defined.
=) operator
54 Data and Data Types
For more information on using operators in your ActionScript, see “Abo u t op era t or s”
on page 137.

About naming variables

Be careful when you start naming variables, because although they can have nearly any name, there are some rules. A variable’s name must follow these rules:
A variable must be an identifier.
NOTE
An identifier is the name of a variable, property, object, function, or method. The first character of an indentifier must be a letter, underscore (_), or dollar sign ($). Each subsequent character can be a number, letter, underscore, or dollar sign.
A variable cannot be a keyword or an ActionScript literal such as true, false, null, or
undefined. For more information on literals, see “About literals” on page 94.
A variable must be unique within its scope (see “About variables and scope” on page 60).
A variable should not be any element in the ActionScript language, such as a class name.
If you don’t follow the rules when you name a variable, you might experience syntax errors or unexpected results. In the following example, if you name a variable document, Flash will generate a compiler error:
// This code works as expected. var helloStr:String = new String(); trace(helloStr.length); // 0 // But if you give a variable the same name as a built-in class... var new:String = "hello"; //error: Identifier expected var helloStr:String = new String(); trace(helloStr.length); // undefined
The ActionScript editor supports code hints for built-in classes and for variables that are based on these classes. If you want Flash to provide code hints for a particular object type that you assign to a variable, you can strictly type the variable. Code hints provide tooltip-style syntax hints and a pop-up menu that helps you write your code quickly.
For example, type the following code:
var members:Array = new Array(); members.
As soon as you type the period (.) in the Actions panel, Flash displays a list of methods and properties available for Array objects.
For recommended coding conventions for naming variables, see “Naming variables”
on page 670.
new and then test your
About variables 55

Using variables in an application

In this section, you use variables in short code snippets of ActionScript. You need to declare and initialize a variable in a script before you can use it in an expression. Expressions are combinations of operands and operators that represent a value. For example, in the expression
i+2, i and 2 are operands, and + is an operator.
If you do not initialize a variable before you use it in an expression, the variable is undefined and may cause unexpected results. For more information on writing expressions, see Chapter
4, “Syntax and Language Fundamentals,” on page 77.
If you use an undefined variable, as shown in the following example, the variable’s value in Flash Player 7 and later will be
var squared:Number = myNum * myNum; trace(squared); // NaN var myNum:Number = 6;
In the following example, the statement that declares and initializes the variable myNum comes first, so
var myNum:Number = 6; var squared:Number = myNum * myNum; trace(squared); // 36
squared can be replaced with a value:
Similar behavior occurs when you pass an undefined variable to a method or function, as shown next.
To compare undefined and defined variables being passed to a function:
1. Drag a Button component to the Stage from the Components panel.
2. Open the Property inspector and type bad_button into the Instance Name text box.
3. Type the following code on Frame 1 of the Timeline.
// Does not work function badClickListener(evt:Object):Void {
getURL(targetUrl);
var targetUrl:String = "http://www.adobe.com"; } bad_button.addEventListener("click", badClickListener);
Select Control > Test Movie, and notice that the button does not work (it doesn’t open the
4.
web page).
5. Drag another Button component onto the Stage. Select the button.
6. Open the Property inspector, and type good_button into the Instance Name text box.
NaN, and your script might produce unintended results:
56 Data and Data Types
7. Add the following ActionScript to Frame 1 of the Timeline (following the previous
ActionScript you added):
// Works function goodClickListener(evt:Object):Void {
var targetUrl:String = "http://www.adobe.com";
getURL(targetUrl); } good_button.addEventListener("click", goodClickListener);
Select Control > Test Movie and click the second button you added to the Stage.
8.
This button properly opens the web page.
The type of data that a variable contains affects how and when the variable’s value changes. Primitive data types, such as strings and numbers, are passed by value, which means the current value of the variable is used rather than a reference to that value. Examples of complex data types include the Array and Object data types.
In the following example, you set change
myNum to 30 (in line 3 of the code), the value of otherNum remains 15 because otherNum doesn’t look to myNum for its value. The otherNum variable contains the value of myNum that it receives (in line 2 of the code).
To use variables in your ActionScript:
1. Create a new Flash document, and save it as var_example.fla.
2. Select Frame 1 of the Timeline, and type the following code into the Actions panel:
var myNum:Number = 15; var otherNum:Number = myNum; myNum = 30; trace(myNum); // 30 trace(otherNum); // 15
myNum to 15 and copy the value into otherNum. When you
When you change myNum to 30 (in line 3 of the code), the value of otherNum remains 15 because value of
3. Select Control > Test Movie to see the values display in the Output panel.
otherNum doesn’t look to myNum for its value. The otherNum variable contains the
myNum that it receives (in line 2 of the code).
About variables 57
4. Now add the following ActionScript after the code you added in step 2:
function sqr(myNum:Number):Number {
myNum *= myNum;
return myNum; } var inValue:Number = 3; var outValue:Number = sqr(inValue); trace(inValue); // 3 trace(outValue); // 9
In the this code, the variable inValue contains a primitive value, 3, so the value passes to
sqr() function, and the returned value is 9. The value of the variable inValue does
the not change, although the value of
5. Select Control > Test Movie to see the values display in the Output panel.
myNum in the function changes.
The Object data type can contain such a large amount of complex information that a variable with this type doesn’t hold an actual value; it holds a reference to a value. This reference is similar to an alias that points to the contents of the variable. When the variable needs to know its value, the reference asks for the contents and returns the answer without transferring the value to the variable.
For information on passing a variable by reference, see “Passing a variable by reference”
on page 58.
Passing a variable by reference
Because the Array and Object data types hold a reference to a value instead of containing its actual value, you need be careful when you work with arrays and objects.
The following example shows how to pass an object by reference. When you create a copy of the array, you actually create only a copy of the reference (or alias) to the array’s contents. When you edit the contents in the second array, you modify both the contents of the first and second array because they both point to the same value.
To pass an object by reference:
1. Select File > New and then select Flash Document to create a new FLA file, and save it as
copybyref.fla.
2. Select Frame 1 of the Timeline, and type the following code into the Actions panel:
var myArray:Array = new Array("tom", "josie"); var newArray:Array = myArray; myArray[1] = "jack"; trace(myArray); // tom,jack trace(newArray); // tom,jack
58 Data and Data Types
3. Select Control > Test Movie to test the ActionScript.
This ActionScript creates an Array object called create the variable second element of
trace() statement sends tom,jack to the Output panel.
NOTE
Flash uses a zero-based index, which means that 0 is the first item in the array, 1 is the second, and so on.
newArray and pass a reference to myArray. When you change the myArray to jack, it affects every variable with a reference to it. The
myArray that has two elements. You
In the following example,
zeroArray() by reference. The function zeroArray() accepts an Array object as a
myArray contains an Array object, so you pass the array to function
parameter and sets all the elements of that array to 0. It can modify the array because the array is passed by reference.
To pass an array by reference:
1. Select File > New and then select Flash Document to create a new FLA file, and save it as
arraybyref.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
function zeroArray (theArr:Array):Void { var i:Number; for (i = 0; i < theArr.length; i++) { theArr[i] = 0; } }
var myArr:Array = new Array(); myArr[0] = 1; myArr[1] = 2; myArr[2] = 3; trace(myArr); // 1,2,3 zeroArray(myArr); trace(myArr); // 0,0,0
Select Control > Test Movie to test your ActionScript.
3.
The first
myArray array (1,2,3). After you call the zeroArray() function and pass a reference to
the subsequent
trace() statement in this ActionScript displays the original contents of the
myArray array, each of the array’s values are overwritten and set to zero. The
trace() statement displays the new contents of the myArray array (0,0,0).
Because you pass the array by reference and not by value, you don’t need to return the updated contents of the array from within the
zeroArray() function.
For more information on arrays, see “About arrays” on page 125.
About variables 59

About variables and scope

A variable’s scope refers to the area in which the variable is known (defined) and can be referenced. The area in which the variable is known might be within a certain timeline or inside a function, or it might be globally known throughout the entire application.For more information about scope, see “About scope and targeting” on page 87.
Understanding variable scope is important when you develop Flash applications with ActionScript. Scope indicates not only when and where you can refer to variables but also for how long a particular variable exists in an application. When you define variables in the body of a function, they cease to exist as soon as the specified function ends. If you try to refer to objects in the wrong scope or to variables that have expired, you get errors in your Flash documents, which lead to unexpected behavior or broken functionality.
There are three types of variable scopes in ActionScript:
Global variables and functions are visible to every timeline and scope in your document.
Therefore, a global variable is defined in all areas of your code.
Timeline variables are available to any script on that timeline.
Local variables are available within the function body in which they are declared
(delineated by curly braces). Therefore, local variables are only defined in a part of your code.
For guidelines on using scope and variables, see Chapter 4, “About scope and targeting,” on
page 87.
NOTE
ActionScript 2.0 classes that you create support public, private, and static variable scopes. For more information, see “About class members” on page 211 and “Controlling
member access in your classes” on page 233.
You cannot strict type global variables. For information and a workaround, see “Global
variables” on page 60.
Global variables
Global variables and functions are visible to every timeline and scope in your document. To declare (or create) a variable with global scope, use the name and do not use the variable
var _global.myName = "George"; // Incorrect syntax for global variable _global.myName = "George"; // Correct syntax for global variable
60 Data and Data Types
myName:
var = syntax. For example, the following code creates the global
_global identifier before the variable
However, if you initialize a local variable with the same name as a global variable, you don’t have access to the global variable while you are in the scope of the local variable, as shown in the following example:
_global.counter = 100; // Declares global variable trace(counter); // Accesses the global variable and displays 100 function count():Void {
for (var counter:Number = 0; counter <= 2; counter++) { // Local variable
trace(counter); // Accesses local variable and displays 0 through 2
} } count(); trace(counter); // Accesses global variable and displays 100
This example simply shows that the global variable is not accessed in the scope of the count() function. However, you could access the global-scoped variable if you prefix it with For example, you could access it if you prefix the counter with
_global as shown in the
_global.
following code:
trace(_global.counter);
You cannot assign strict data types to variables that you create in the _global scope, because you have to use the var keyword when you assign a data type. For example, you couldn't do:
_global.foo:String = "foo"; //syntax error var _global.foo:String = "foo"; //syntax error
The Flash Player version 7 and later security sandbox enforces restrictions when accessing global variables from SWF files loaded from separate security domains. For more information, see Chapter 16, “Understanding Security,” on page 631.
Timeline variables
Timeline variables are available to any script on that particular timeline. To declare timeline variables, use the is available to that frame and all following frames, as shown in the following example.
To use timeline variables in a document:
1. Create a new Flash document, and name it timelinevar.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
var myNum:Number = 15; /* initialized in Frame 1, so it's available to
all frames */
Select Frame 20 of the Timeline.
3.
4. Select Insert > Timeline > Blank Keyframe.
5. With the new keyframe selected, type the following ActionScript into the Actions panel:
trace(myNum);
var statement and initialize them in any frame in the timeline. The variable
About variables 61
6. Select Control > Test Movie to test the new document.
The value 15 appears in the Output panel after approximately a second. Because Flash documents loop by default, the value 15 continually traces in the Output panel every time the playhead reaches Frame 20 in the Timeline. To stop the looping action, add after the
trace() statement.
stop();
You must declare a timeline variable before trying to access it in a script. For example, if you put the code Frame 20 cannot access
var myNum:Number = 15; in Frame 20, any scripts attached to a frame before
myNum and are undefined instead of containing the value 15.
Local variables
When you use the var statement inside a function block, you declare local variables. When you declare a local variable within a function block (also called function definition), it is defined within the scope of the function block, and expires at the end of the function block. Therefore, the local variable only exists within that function.
For example, if you declare a variable named that variable will not be available outside of the function.
function localScope():Void {
var myStr:String = "local"; } localScope(); trace(myStr); // Undefined, because myStr is not defined globally
If the variable name you use for your local variable is already declared as a timeline variable, the local definition takes precedence over the timeline definition while the local variable is in scope. The timeline variable will still exist outside of the function. For example, the following code creates a timeline string variable named same name inside the
scopeTest() function. The trace statement inside the function
generates the local definition of the variable, but the generates the timeline definition of the variable.
var str1:String = "Timeline"; function scopeTest():Void {
var str1:String = "Local";
trace(str1); // Local } scopeTest(); trace(str1); // Timeline
In the next example, you can see how certain variables live only for the life of a specific function and can generate errors if you try to refer to the variable outside the scope of that function.
myStr within a function named localScope,
str1, and then creates a local variable of the
trace statement outside the function
62 Data and Data Types
To use local variables in an application:
1. Create a new Flash document.
2. Open the Actions panel (Window > Actions) and add the following ActionScript to Frame
1 of the Timeline:
function sayHello(nameStr:String):Void {
var greetingStr:String = "Hello, " + nameStr;
trace(greetingStr); } sayHello("world"); // Hello, world trace(nameStr); // undefined trace(greetingStr); // undefined
Select Control > Test Movie to test the document.
3.
Flash displays the string “Hello, world” in the Output panel and displays the values of the current scope. You can only reference the
sayHello function. When the function exits, the variables cease to exist.
The variables local variable; it exists only inside the
var myArr:Array = new Array(); function initArray(arrayLength:Number):Void { var i:Number; for(i = 0; i < arrayLength; i++) { myArr[i] = i + 1; } } trace(myArr); // <blank> initArray(3); trace(myArr); // 1,2,3 trace(i); // undefined
NOTE
It’s also common to see the following syntax for a for loop: for (var i:Number = 0; i < arrayLength; i++) {...}.
nameStr and greetingStr because the variables are no longer available in
nameStr and greetingStr in the execution of
i and j are often used as loop counters. In the following example, you use i as a
initArray() function:
undefined for
This example displays undefined in the Flash test environment because the variable i isn’t defined in the main timeline. It exists only in the
initArray() function.
You can use local variables to help prevent name conflicts, which can cause unexpected results in your application. For example, if you use
age as a local variable, you could use it to store a
person’s age in one context and the age of a person’s child in another context. There is no conflict in this situation because you are using these variables in separate scopes.
About variables 63
It’s good practice to use local variables in the body of a function so the function can act as an independent piece of code. You can change a local variable only within its own block of code. If an expression in a function uses a global variable, code or events outside the function can change its value, which changes the function.
You can assign a data type to a local variable when you declare it, which helps prevent assigning the wrong type of data to an existing variable. For more information, see “Ab ou t
assigning data types and strict data typing” on page 45.

About loading variables

In the following sections, you load variables from the server in different ways or into a document from a URL string or FlashVars (you can use FlashVars to pass variables into Flash) in your HTML code. These practices demonstrate that there are several ways to use variables outside a SWF file.
You can find more information on loading variables (such as name/value pairs) in Chapter 15,
“Working with External Data,” on page 589.
You can use variables in different ways in a SWF file, depending on what you need the variables for. For more information, see the following topics:
“Using variables from the URL” on page 64
“Using FlashVars in an application” on page 67
“Loading variables from a server” on page 68
Using variables from the URL
When you develop an application or simple example in Flash, you might want to pass values from an HTML page into your Flash document. The passed values are sometimes known as the query string, or URL-encoded variables. URL variables are useful if you want to create a menu in Flash, for example. You can initialize the menu to show the correct navigation by default. Or you can build an image viewer in Flash and define a default image to show on the website.
To use URL variables in a document:
1. Create a Flash document, and name it urlvariables.fla.
2. Select File > Save As, and save the document on your desktop.
3. Select Frame 1 of the Timeline, and add the following code in the Actions panel:
this.createTextField("myTxt", 100, 0, 0, 100, 20); myTxt.autoSize = "left"; myTxt.text = _level0.myURL;
64 Data and Data Types
4. Select Control > Test Movie to test the SWF file in Flash Player.
The text field displays
undefined. If you want to make sure the variables are properly
defined before you proceed, you need to check for the existence of the variables in Flash. You can do this by checking to see if they are undefined.
5. To check to see if the variable is defined, modify the ActionScript you added to the Actions
panel in step 3 to match the following code. Add the code that appears in bold:
this.createTextField("myTxt", 100, 0, 0, 100, 20); myTxt.autoSize = "left";
if (_level0.myURL == undefined) {
myTxt.text = "myURL is not defined"; } else {
myTxt.text = _level0.myURL; }
When you publish your Flash document, an HTML document is created by default in the same directory as the SWF file. If an HTML file was not created, select File > Publish settings, and make sure you select HTML in the Formats tab. Then publish your document again.
The following code demonstrates the HTML in the document that is responsible for embedding a Flash document in an HTML page. You need to look at this HTML to understand how URL variables work in the following step (where you add additional code for URL variables).
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/
swflash.cab#version=8,0,0,0" width="550" height="400"
id="urlvariables" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="urlvariables.swf" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="urlvariables.swf" quality="high" bgcolor="#ffffff"
width="550" height="400" name="urlvariables" align="middle"
allowScriptAccess="sameDomain" type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer" /> </object>
To pass variables from the generated HTML document to your Flash document, you can
6.
pass variables after the path and filename (urlvariables.swf). Add the bold text to the HTML file that was generated on your desktop.
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/
swflash.cab#version=8,0,0,0" width="550" height="400"
id="urlvariables" align="middle">
About variables 65
<param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="urlvariables.swf?myURL=http://
weblogs.macromedia.com" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="urlvariables.swf?myURL=http://weblogs.macromedia.com"
quality="high" bgcolor="#ffffff" width="550" height="400"
name="urlvariables" align="middle" allowScriptAccess="sameDomain"
type="application/x-shockwave-flash" pluginspage="http://
www.adobe.com/go/getflashplayer" /> </object>
If you want to pass multiple variables to Flash, you need to separate the name/values pairs
7.
with an ampersand (&). Find the following code from step 6:
?myURL=http://weblogs.macromedia.com
Replace it with the following text:
?myURL=http://weblogs.macromedia.com&myTitle=adobe+News+Aggregator
Remember, you need to make the same changes to both the object tag and the embed tag to maintain consistency between all browsers. You might notice that the words are separated by + punctuators. The words are separated this way because the values are URL­encoded and the + punctuator represents a single blank space.
NOTE
For a list of common URL-encoded special characters, see the Flash TechNote,
URL Encoding: Reading special characters from a text file.
Because the ampersand (
&) serves as a delimiter for different name/value pairs, if the values
you are passing contain ampersands, unexpected results might occur. Given the nature of name/value pairs and parsing, if you had the following values being passed to Flash:
my.swf?name=PB+&+J&flavor=strawberry+rhubarb
Flash would build the following variables (and values) into the root scope:
'name': 'PB ' (note space at end of value) ' J': '' (note space at beginning of variable name and an empty value) 'flavor': 'strawberry rhubarb'
To avoid this, you need to escape the ampersand (&) character in the name/value pair with its URL-encoded equivalent (
8. Open the urlvariables.html document, and find the following code:
?myURL=http://weblogs.macromedia.com&myTitle=Adobe+News+Aggregator
%26).
Replace it with the following code:
?myURL=PB+%26+J&flavor=strawberry+rhubarb
66 Data and Data Types
9. Save the revised HTML, and test your Flash document again.
You see that Flash created the following name/value pairs.
'name': 'PB & J' 'flavor': 'strawberry rhubarb'
NOTE
All browsers will support string sizes as large as 64K (65535 bytes) in length. FlashVars must be assigned in both the object and embed tags in order to work on all browsers.
Using FlashVars in an application
Using FlashVars to pass variables into Flash is similar to passing variables along the URL in the HTML code. With FlashVars, instead of passing variables after the filename, variables are passed in a separate
To use FlashVars in a document:
1. Create a new Flash document, and name it myflashvars.fla.
2. Select File > Publish Settings and make sure that HTML is selected, and then click OK to
close the dialog box.
3. Add the following ActionScript to Frame 1 of the main Timeline:
this.createTextField("myTxt", 100, 0, 0, 100, 20); myTxt.autoSize = "left"; if (_level0.myURL == undefined) {
myTxt.text = "myURL is not defined"; } else {
myTxt.text = _level0.myURL; }
NOTE
By default, HTML code publishes to the same location as myflashvars.fla.
param tag as well as in the embed tag.
Select File > Publish to publish the SWF and HTML files.
4.
5. Open the directory containing the published files (where you saved myflashvars.fla on your
hard drive) and open the HTML document (myflashvars.html by default) in an HTML editor such as Dreamweaver or Notepad.
6. Add the code that appears in bold below, so your HTM L document matches the follo wing:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/
swflash.cab#version=8,0,0,0" width="550" height="400" id="myflashvars"
align="middle">
About variables 67
<param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="myflashvars.swf" />
<param name="FlashVars" value="myURL=http://weblogs.adobe.com/">
<param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="myflashvars.swf" FlashVars="myURL=http://weblogs.adobe.com/"
quality="high" bgcolor="#ffffff" width="550" height="400"
name="myflashvars" align="middle" allowScriptAccess="sameDomain"
type="application/x-shockwave-flash" pluginspage="http://
www.adobe.com/go/getflashplayer" /> </object>
This code passes a single variable called myURL, which contains the string
http://weblogs.macromedia.com. When the SWF file loads, a property named myURL
is created in the _level0 scope. One of the advantages of using FlashVars or passing variables along the URL is that the variables are immediately available in Flash when the SWF file loads. This means you don’t have to write any functions to check if the variables have finished loading, which you would need to do if you loaded variables using LoadVars or XML.
7. Save your changes to the HTML document, and then close it.
8. Double click myflashvars.html to test the application.
The text
http://weblogs.macromedia.com, a variable in the HTML file, appears in the
SWF file.
NOTE
All browsers will support string sizes as large as 64K (65,535 bytes) in length. FlashVars must be assigned in both the object and embed tags in order to work on all browsers.
Loading variables from a server
There are several ways to load variables into Flash from external sources (such as text files, XML documents, and so on). You can find much more information on loading variables, including name/value pairs, in Chapter 15, “Working with External Data,” on page 589.
In Flash, you can easily load variables using the LoadVars class, as shown in the next example.
68 Data and Data Types
To load variables from a server:
1. Create a new Flash document.
2. Select Frame 1 of the Timeline, and add the following ActionScript in the Actions panel:
var my_lv:LoadVars = new LoadVars(); my_lv.onLoad = function(success:Boolean):Void {
if (success) {
trace(this.dayNames); // Sunday,Monday,Tuesday,...
} else {
trace("Error");
} } my_lv.load("http://www.helpexamples.com/flash/params.txt");
This code loads a text file from a remote server and parses its name/value pairs.
TIP
Download or view the text file (http://www.helpexamples.com/flash/params.txt) in a browser if you want to know how the variables are formatted.
3. Select Control > Test Movie to test the document.
If the file successfully loads, the the value of to
false and the Output panel displays the text Error.
dayNames. If the text file cannot be downloaded, the success argument is set
complete event is called and the Output panel displays

Using variables in a project

When you build animations or applications with Flash, there are very few situations in which you don’t need to use any kind of variable in your project. For example, if you build a login system, you might need variables to determine whether the user name and password are valid, or whether they are filled in at all.
You can find more information on loading variables (such as name/value pairs) in Chapter 15,
“Working with External Data,” on page 589.
In the following example, you use variables to store the path of an image you are loading with the Loader class, a variable for the instance of the Loader class, and a couple of functions that are called depending on whether the file is successfully loaded or not.
About variables 69
To use variables in a project:
1. Create a new Flash document, and save it as imgloader.fla.
2. Select Frame 1 of the Timeline, and add the following ActionScript to the Actions panel:
/* Specify default image in case there wasn't a value passed using
FlashVars. */ var imgUrl:String = "http://www.helpexamples.com/flash/images/
image1.jpg"; if (_level0.imgURL != undefined) {
// If image was specified, overwrite default value.
imgUrl = _level0.imgURL; }
this.createEmptyMovieClip("img_mc", 10); var mclListener:Object = new Object(); mclListener.onLoadInit = function(target_mc:MovieClip):Void {
target_mc._x = (Stage.width - target_mc._width) / 2;
target_mc._y = (Stage.height - target_mc._height) / 2; } mclListener.onLoadError = function(target_mc:MovieClip):Void {
target_mc.createTextField("error_txt", 1, 0, 0, 100, 20);
target_mc.error_txt.autoSize = "left";
target_mc.error_txt.text = "Error downloading specified image;\n\t" +
target_mc._url; } var myMCL:MovieClipLoader = new MovieClipLoader(); myMCL.addListener(mclListener); myMCL.loadClip(imgUrl, img_mc);
The first line of code specifies the image that you want to dynamically load into your Flash document. Next, you check whether a new value for
imgURL was specified using
FlashVars or URL-encoded variables. If a new value was specified, the default image URL is overwritten with the new value. For information on using URL variables, see “Using
variables from the URL” on page 64. For information on FlashVars, see “Using FlashVars in an application” on page 67.
The next couple of lines of code define the MovieClip instance, and a Listener object for the future MovieClipLoader instance. The MovieClipLoader’s Listener object defines two event handlers,
onLoadInit and onLoadError. The handlers are invoked when the image
successfully loads and initializes on the Stage, or if the image fails to load. Then you create a MovieClipLoader instance, and use the
addListener() method to add the previously
defined listener object to the MovieClipLoader. Finally, the image is downloaded and triggered when you call the
MovieClipLoader.loadClip() method, which specifies the
image file to load and the target movie clip to load the image into.
70 Data and Data Types
3. Select Control > Test Movie to test the document.
Because you’re testing the Flash document in the authoring tool, no value for
imgUrl will
be passed by FlashVars or along the URL, and therefore the default image displays.
4. Save the Flash document and select File > Publish to publish the file as a SWF and HTML
document.
NOTE
Make sure that Flash and HTML are both selected in the Publish Settings dialog box. Select File > Publish Settings and then click the Formats tab. Then, select both options.
5. If you test your document in the Flash tool (select Control > Test Movie) or in a local
browser (File > Publish Preview > HTML), you will see that the image centers itself both vertically and horizontally on the Stage.
6. Edit the generated HTML document in an editor (such as Dreamweaver or Notepad), and
modify the default HTML to match the following text:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/
swflash.cab#version=8,0,0,0" width="550" height="400" id="imgloader"
align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="imgloader.swf" />
<param name="FlashVars" value="imgURL=http://www.helpexamples.com/flash/
images/image2.jpg">
<param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="imgloader.swf" quality="high" FlashVars="imgURL=http://
www.helpexamples.com/flash/images/image2.jpg" bgcolor="#ffffff"
width="550" height="400" name="imgloader" align="middle"
allowScriptAccess="sameDomain" type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer" /> </object>
Test the HTML document to see the changes. An image that you specify in the HTML
7.
code appears in the SWF file.
To modify this example to use your own images, you would modify the FlashVars value (the string inside the double quotes).
About variables 71

Organizing data in objects

You might already be used to objects that you place on the Stage. For example, you might have a MovieClip object on the Stage, and this object contains other movie clips inside it. Text fields, movie clips, and buttons are often called objects when you place them on the Stage.
Objects, in ActionScript, are collections of properties and methods. Each object has its own name, and it is an instance of a particular class. Built-in objects are from classes that are predefined in ActionScript. For example, the built-in Date class provides information from the system clock on the user’s computer. You can use the built-in LoadVars class to load variables into your SWF file.
You can also create objects and classes using ActionScript. You might create an object to hold a collection of data, such as a person’s name, address. and telephone number. You might create an object to hold color information for an image. Organizing data in objects can help keep your Flash documents more organized. For general information on creating a custom class to hold a collection of methods and properties, see “Writing custom class files” on page 196. For detailed information on both built-in and custom classes, see Chapter 6, “Classes,” on
page 187.
There are several ways to create an object in ActionScript. The next example creates simple objects in two different ways, and then loops over the contents of those objects.
To create simple objects in Flash:
1. Create a new Flash document, and save it as simpleObjects.fla.
2. Select Frame 1 of the Timeline, and type the following ActionScript into the Actions panel:
// The first way var firstObj:Object = new Object(); firstObj.firstVar = "hello world"; firstObj.secondVar = 28; firstObj.thirdVar = new Date(1980, 0, 1); // January 1, 1980
This code, which is one way to create a simple object, creates a new object instance and defines a few properties within the object.
3. Now enter the following ActionScript after the code you entered in step 2.
// The second way var secondObj:Object = {firstVar:"hello world", secondVar:28,
thirdVar:new Date(1980, 0, 1)};
This is another way of creating an object. Both objects are equivalent. This code above creates a new object and initializes some properties using the object shorthand notation.
72 Data and Data Types
4. To loop over each of the previous objects and display the contents of objects, add the
following ActionScript on Frame 1 of the Timeline (after the code you’ve already entered):
var i:String; for (i in secondObj) {
trace(i + ": " + secondObj[i]); }
Select Control > Test Movie, and the following text appears in the Output panel:
5.
firstVar: hello world secondVar: 28 thirdVar: Tue Jan 1 00:00:00 GMT-0800 1980
NOTE
The variables might not necessarily appear in this order in the Output panel. You cannot guarantee the ordering when you use a for..in loop; the player returns the contents of an object in an unpredictable order.
You can also use arrays to create objects. Instead of having a series of variables such as
firstname1, firstname2, and firstname3 to represent a collection of variables, you can
make an array of objects to represent the same data. This technique is demonstrated next.
To use an array to create an object:
1. Create a new Flash document, and save it as arrayObject.fla.
2. Select Frame 1 of the Timeline, and type the following ActionScript into the Actions panel:
var usersArr:Array = new Array(); usersArr.push({firstname:"George"}); usersArr.push({firstname:"John"}); usersArr.push({firstname:"Thomas"});
The benefit of organizing variables into arrays and objects is that it becomes much easier to loop over the variables and see the values, as shown in the following step.
3. Type the following code after the ActionScript you added in step 2.
var i:Number; for (i = 0; i < usersArr.length; i++) {
trace(usersArr[i].firstname); // George, John, Thomas }
Select Control > Test Movie, and the following text appears in the Output panel:
4.
George John Thomas
Organizing data in objects 73
The following example presents another way to loop over objects. In this example, an object is created and looped over using a
for..in loop, and each property appears in the Output
panel:
var myObj:Object = {var1:"One", var2:"Two", var3:18, var4:1987}; var i:String; for (i in myObj) {
trace(i + ": " + myObj[i]); } //outputs the following: /* var1: One var2: Two var3: 18 var4: 1987 */
For information on creating for loops, see Chapter 4, “Using for loops,” on page 119. For information on for..in loops, see “Using for..in loops” on page 120. For more information on objects, see Chapter 6, “Classes,” on page 187.

About casting

ActionScript 2.0 lets you cast one data type to another. Casting an object to a different type means you convert the value that the object or variable holds to a different type.
The results of a type cast vary depending on the data types involved. To cast an object to a different type, you wrap the object name in parentheses ( the new type. For example, the following code takes a Boolean value and casts it to an integer.
var myBoolean:Boolean = true; var myNumber:Number = Number(myBoolean);
For more information on casting, see the following topics:
“About casting objects” on page 75
()) and precede it with the name of
74 Data and Data Types

About casting objects

The syntax for casting is type(item), where you want the compiler to behave as if the data type of the item is
null if the cast fails at runtime (this occurs in files published for Flash Player 7 or later; files
published for Flash Player 6 do not have runtime support for failed casts). If the cast succeeds, the function call returns the original object. However, the compiler cannot determine whether a cast will fail at runtime and won’t generate compile-time errors in those cases.
The following code shows an example:
// Both the Cat and Dog classes are subclasses of the Animal class function bark(myAnimal:Animal) {
var foo:Dog = Dog(myAnimal);
foo.bark(); } var curAnimal:Animal = new Dog(); bark(curAnimal); // Will work curAnimal = new Cat(); bark(curAnimal); // Won't work
In this example, you asserted to the compiler that foo is a Dog object, and therefore the compiler assumes that that the cast will fail (that is, that you tried to cast a Cat object to an Animal type), so no compile-time error occurs. However, if you include a check in your script to make sure that the cast succeeds, you can find casting errors at runtime, as shown in the following example.
function bark(myAnimal:Animal) { var foo:Dog = Dog(myAnimal); if (foo) { foo.bark(); } }
You can cast an expression to an interface. If the expression is an object that implements the interface or has a base class that implements the interface, the cast succeeds. If not, the cast fails.
NOTE
Casting to null or undefined returns undefined.
type. Casting is essentially a function call, and the function call returns
foo.bark(); is a legal statement. However, the compiler doesn’t know
You can’t override primitive data types that have a corresponding global conversion function with a cast operator of the same name. This is because the global conversion functions have precedence over the cast operators. For example, you can’t cast to Array because the
Array()
conversion function takes precedence over the cast operator.
About casting 75
This example defines two string variables (firstNum and secondNum), which are added together. The initial result is that the numbers are concatenated instead of added because they are a String data type. The second trace statement converts both numbers to a Number data type before performing the addition that yields the proper result. Data conversion is important when working with data loaded using XML or FlashVars, as shown in the following example:
var firstNum:String = "17"; var secondNum:String = "29"; trace(firstNum + secondNum); // 1729 trace(Number(firstNum) + Number(secondNum)); // 46
For more information on data conversion functions, see the entry for each conversion function in ActionScript 2.0 Language Reference:
Number function, Object function, and String function.
Array function, Boolean function,
76 Data and Data Types
CHAPTER 4

Syntax and Language Fundamentals

Learning ActionScript syntax and statements is like learning how to put together words to make sentences, which you can then put together into paragraphs. ActionScript can be as simple. For example, in English, a period ends a sentence; in ActionScript, a semicolon ends a statement. In the ActionScript language, you can type a a movie clip instance or a SWF file from looping. Or you can write thousands of lines of code to power an interactive banking application. As you can see, ActionScript can do very simple or very complex things.
In Chapter 3, “Data and Data Types,” you learned how the ActionScript language uses data, and how you can format it in your code. This chapter demonstrates how you can form statements in ActionScript using syntax. It contains many short code snippets and some examples to demonstrate fundamental language concepts. Upcoming chapters contain longer and increasingly involved code examples that combine and facilitate the fundamentals you learn in this chapter.
The general rules described in this section apply to all ActionScript. Most ActionScript terms also have individual requirements; for the rules for a specific term, see its entry in the ActionScript 2.0 Language Reference.
Applying the basics of ActionScript in a way that creates elegant programs can be a challenge for users who are new to ActionScript. For more information on how to apply the rules described in this section, see Chapter 17, “Best Practices and Coding Conventions for
ActionScript 2.0,” on page 665.
NOTE
You add ActionScript directly to a frame on the Timeline within this chapter. In later chapters, you use classes to separate your ActionScript from the FLA file.
stop() action to stop the playhead of
4
77
For more information on working with ActionScript syntax and language fundamentals, see the following topics:
About syntax, statements, and expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
About dot syntax and target paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
About language punctuators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
About constants and keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
About statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
About arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
About operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

About syntax, statements, and expressions

The ActionScript language is made up of the built-in classes that make up the ActionScript language. You need to use correct ActionScript syntax to form statements so the code compiles and runs correctly in Flash. In this case, syntax refers to the grammar and spelling of a language that you program with. The compiler cannot understand incorrect syntax, so you see errors or warnings displayed in the Output panel when you try to test the document in the test environment. Therefore, syntax is a collection of rules and guidelines that help you form correct ActionScript.
A statement is an instruction you give the FLA file to do something, such as to perform a particular action. For example, you can use a conditional statement to determine whether something is true or exists. Then you might execute actions that you specify, such as functions or expressions, based on whether the condition is true or not. The conditional statement and evaluates a condition to determine the next action that should occur in your code.
// if statement if (condition) { // statements; }
For more information on statements, see “About statements” on page 103.
if statement is a
78 Syntax and Language Fundamentals
Expressions, different from statements, are any legal combination of ActionScript symbols that represent a value. Expressions have values, while values and properties have types. An expression can consist of operators and operands, values, functions, and procedures. The expression follows ActionScript rules of precedence and of association. Typically, Flash Player interprets the expression and then returns a value that you can use in your application.
For example, the following code is an expression:
x + 2
In the previous expression, x and 2 are operands and + is an operator. For more information on operators and operands, see “About operators” on page 137. For more information on objects and properties, see “Object data type” on page 42.
The way you format your ActionScript also determines how maintainable your code is. For example, it’s difficult to read the logic of a FLA file that doesn’t contain indents or comments, or contains inconsistent formatting and naming conventions. When you indent blocks of ActionScript (such as loops and
if statements), the code is easier to read and debug if you
encounter problems. For more information about formatting ActionScript, see “Formatting
ActionScript syntax” on page 697. You can also see proper formatting of ActionScript in
these sections.
For more information on syntax and language fundamentals, see the following topics:
“Differences between ActionScript and JavaScript”
“About case sensitivity”

Differences between ActionScript and JavaScript

ActionScript is similar to the core JavaScript programming language. You don’t need to know JavaScript to use and learn ActionScript; however, if you know JavaScript, ActionScript will seem familiar.
This manual does not attempt to teach general programming. There are many resources that provide more information about general programming concepts and the JavaScript language.
The ECMAScript (ECMA-262) edition 3 language specification is derived from
JavaScript and serves as the international standard for the JavaScript language. ActionScript is based on this specification. For more information, see www.ecma-
international.org/publications/standards/Ecma-262.htm.
The Java Technology site has tutorials on object-oriented programming (http://
java.sun.com/docs/books/tutorial/java/index.html) that are targeted for the Java language
but are useful for understanding concepts that you can apply to ActionScript.
About syntax, statements, and expressions 79
Some of the differences between ActionScript and JavaScript are described in the following list:
ActionScript does not support browser-specific objects such as Document, Window,
and Anchor.
ActionScript does not completely support all the JavaScript built-in objects.
ActionScript does not support some JavaScript syntax constructs, such as statement labels.
In ActionScript, the eval() function can perform only variable references.
ActionScript 2.0 supports several features that are not in the ECMA-262 specification,
such as classes and strong typing. Many of these features are modeled after the ECMAScript (ECMA-262) edition 3 language specification (see www.ecma-
international.org/publications/standards/Ecma-262.htm).
ActionScript does not support regular expressions using the RegExp object. However,
Adobe Central does support the RegExp object. For more information on Adobe Central, see www.adobe.com/products/central.

About case sensitivity

When you write ActionScript for Flash Player 7 and later, your code is case-sensitive. This means that variables with slightly different capitalization are considered different from each other. The following ActionScript code shows this:
// use mixed capitalization var firstName:String = "Jimmy"; // use all lower case trace(firstname); // undefined
Or you could write the following:
// In file targeting Flash Player 8 // and either ActionScript 1.0 or ActionScript 2.0 // // Sets properties of two different objects cat.hilite = true; CAT.hilite = true;
// Creates three different variables var myVar:Number = 10; var myvar:Number = 10; var mYvAr:Number = 10;
NOTE
It is not a good practice to differentiate between variables, or any identifier, using different case. For more information on naming variables, see Chapter 17, “Best
Practices and Coding Conventions for ActionScript 2.0,” on page 665.
80 Syntax and Language Fundamentals
When you publish for versions of Flash Player (Flash Player 6 and earlier), Flash traces the
Jimmy in the Output panel. Because Flash Player 7 and later versions are case-sensitive,
string
firstName and firstname are two separate variables (when you use either ActionScript 1.0
or ActionScript 2.0). This is an important concept to understand. If you created FLA files for Flash Player 6 or earlier with nonmatching capitalization in your variables, your functionality and files might break during conversion of the file or application that targets a newer version of the Flash Player.
Therefore, it’s good practice to follow consistent capitalization conventions, such as those used in this manual. Doing so also makes it easier to differentiate between variables, classes, and function names. Do not use case to make two identifiers differ. Change the instance, variable, or class name—not just the case. For more information on coding conventions, see
Chapter 17, “Best Practices and Coding Conventions for ActionScript 2.0,” on page 665.
Case sensitivity can have a large impact when you work with a web service that uses its own rules for variable naming and for the case that variables are in when they are returned to the SWF file from the server. For example, if you use a ColdFusion web service, property names from a structure or object might be all uppercase, such as
FIRSTNAME. Unless you use the same
case in Flash, you might experience unexpected results.
NOTE
Case sensitivity also affects external variables that you load into a SWF file, such as those loaded with
LoadVars.load().
Case sensitivity is implemented for external scripts, such as ActionScript 2.0 class files, scripts that you import using the
#include command, and scripts in a FLA file. If you encounter
runtime errors and are exporting to more than one version of Flash Player, you should review both external script files and scripts in FLA files to confirm that you used consistent capitalization.
Case sensitivity is implemented on a per-SWF file basis. If a strict (case-sensitive) Flash Player 8 application calls a nonstrict Flash Player 6 SWF file, ActionScript executed in the Player 6 SWF file is nonstrict. For example, if you use
loadMovie() to load a Flash Player 6 SWF file
into a Flash Player 8 SWF file, the version 6 SWF file remains case-insensitive, while the version 8 SWF file is treated as case-sensitive.
When syntax coloring is enabled, language elements written with correct capitalization are blue by default. For more information, see “About reserved words” on page 103.
About syntax, statements, and expressions 81

About dot syntax and target paths

In ActionScript, you use a dot (.) operator (dot syntax) to access properties or methods that belong to an object or instance on the Stage. You also use the dot operator to identify the target path to an instance (such as a movie clip), variable, function, or object.
A dot syntax expression begins with the name of the object or movie clip, followed by a dot, and it ends with the element you want to specify. The following sections demonstrate how to write dot syntax expressions.
To control a movie clip, loaded SWF file, or button, you must specify a target path. Target paths are hierarchical addresses of movie clip instance names, variables, and objects in a SWF file. In order to specify a target path for a movie clip or button, you must assign an instance name to the movie clip or button. You name a movie clip instance by selecting the instance and typing the instance name in the Property inspector. Or you can specify the instance name with code if you create the instance using ActionScript. You can use the target path to assign an action to a movie clip or to get or set the value of a variable or property.
For more information on assigning an instance name and using dot syntax to target an instance, see the following topics:
“About using dot syntax to target an instance” on page 82.
“About scope and targeting” on page 87
“Using the Target Path button” on page 88
“About slash syntax” on page 88
For more information on objects and properties, see “Object data type” on page 42.

About using dot syntax to target an instance

To write ActionScript that controls an instance such as a movie clip or manipulates assets in a loaded SWF file, you must specify its name and its address in code. This is called a target path. To target (or address) objects in a SWF file, you use dot syntax (also called dot notation). For example, you need to target a movie clip or button instance before you can apply an action to it. Dot syntax helps you create a path to the instance you need to target. The path to the instance that you target is sometimes called the target path.
A FLA file has a particular hierarchy. You can create instances on the Stage or you can use ActionScript. You can even create instances that are inside other instances. Or you might have instances that nest within several other instances. You can manipulate any instance as long as you name it.
82 Syntax and Language Fundamentals
You name instances using an instance name, which you can specify in two different ways (both demonstrated below):
Manually by selecting an instance and typing an instance name in the Property inspector
(when an instance is on the Stage).
Dynamically by using ActionScript. You create an instance using ActionScript and assign
it an instance name when you create it.
To assign the instance an instance name in the Property inspector, type a name into the Instance Name text box.
You can also give an instance name to an object you create using ActionScript. It can be as simple as the following code:
this.createEmptyMovieClip("pic_mc", this.getNextHighestDepth()); pic_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");
This code creates a new movie clip and assigns it the instance name pic_mc. Then, you can manipulate the
pic_mc instance using code, such as loading an image into it as demonstrated
in the previous code.
For more information on working with scope, see “About scope and targeting” on page 87 and “About variables and scope” on page 60.
Targeting an instance
If you want something to work in your SWF file, you need to target that instance and then tell it to do something, such as assigning it an action or changing its properties. You usually need to define where that instance is in the SWF file (for example, what timeline it’s on or what instance it’s nested within) by creating the target path. Remember that you have given many of the instances in your FLA file instance names, and then you added code to the FLA file that uses those instance names. When you do this, you target that particular instance and then tell it to do something (such as move the playhead or open a web page). For more information on objects and properties, see “Object data type” on page 42.
To target an instance:
1. Select File > New and select Flash Document.
2. Select File > Save As and name the file target.fla.
3. Use the Oval tool to draw a shape on the Stage. Draw an oval of any size and color.
4. Use the Selection tool to select the oval on the Stage.
TIP
Remember to select the stroke and fill if necessary.
About dot syntax and target paths 83
5. Select Modify > Convert to Symbol, select the Movie Clip option, and then click OK to
create the symbol.
6. Select the movie clip on the Stage and give it the instance name myClip in the
Property inspector.
7. Insert a new layer and rename the layer actions.
8. Add the following ActionScript to Frame 1 of the actions layer:
myClip._xscale = 50;
This line of code targets the myClip instance on the Stage. The ActionScript scales the instance to half its original width. Because the ActionScript is on the same timeline as the movie clip symbol, you only need to target the instance using the instance name. If the instance was on a different timeline or nested within another instance, you would need to modify the target path accordingly.
Targeting a nested instance
You can also target instances that are nested inside other instances. Perhaps you want to place a second movie clip instance inside of the myClip instance from the exercise in “Targeting an
instance” on page 83. You can also target that nested instance using ActionScript. Before you
proceed with the following exercise, you need to complete the exercise in “Targeting an
instance” on page 83, and then follow these steps to target a nested instance.
To target a nested instance:
1. Open target.fla from the procedure on targeting an instance, and rename it target2.fla.
2. Double-click the myClip instance on the Stage.
3. Select the Oval tool and draw another oval inside of the myClip instance.
4. Select the new shape, and then select Modify > Convert to Symbol.
5. Select the Movie Clip option and click OK.
6. Select the new instance, and type myOtherClip in the Instance Name text box of the
Property inspector.
7. Click Scene 1 in the edit bar to return to the main Timeline.
8. Add the following ActionScript to Frame 1 of the actions layer:
myClip.myOtherClip._xscale = 50;
This ActionScript resizes the myOtherClip instance to 50% of its current width. Because the target.fla file modified the myClip instances is a nested symbol, you’ll notice that myOtherClip will be 25 percent of the original width.
_xscale property, and the myOtherClip
84 Syntax and Language Fundamentals
If you work with nested movie clips that have their own timelines, you can manipulate the playhead in a nested instance’s timeline using code similar to the following snippet:
myClip.nestedClip.gotoAndPlay(15); myClip.someOtherClip.gotoAndStop("tweenIn");
Notice that the clip that you manipulate (such as nestedClip) appears right before the action. You’ll notice this trend in upcoming sections.
You aren’t limited to accessing predefined methods and properties of instances on the Stage, as demonstrated in the previous examples. You can also set a variable within a movie clip, as seen in the following code, which sets a variable in the starClip movie clip:
starClip.speed = 1.1; starClip.gravity = 0.8;
If either the speed or gravity variables existed previously in the starClip movie clip instance, the previous values would have been overwritten as soon as the new values were set. You are able to add new properties to the starClip movie clip, because the MovieClip class was defined with the
dynamic keyword. The dynamic keyword specifies that objects based on the
specified class (in this case MovieClip) can add and access dynamic properties at runtime. For more information about the dynamic statement, see dynamic statement in the ActionScript
2.0 Language Reference.
Targeting dynamic instances and loaded content
You can also create an object using ActionScript and target it using a target path afterwards. For example, you can use the following ActionScript to create a movie clip. Then you can change the rotation of that movie clip using ActionScript, as shown in the next example:
To target a dynamically created movie clip instance:
1. Create a new Flash document and save the file as targetClip.fla.
2. Insert a new layer and rename the layer actions.
3. Add the following ActionScript to Frame 1 of the actions layer:
this.createEmptyMovieClip("rotateClip", this.getNextHighestDepth()); trace(rotateClip); rotateClip._rotation = 50;
Select Control > Test Movie to test your document.
4.
You can tell that you created a movie clip because of the
trace statement, but you cannot
see anything on the Stage. Even though you added code that creates a movie clip instance, you won’t see anything on the Stage unless you add something to the movie clip. For example, you might load an image into the movie clip.
5. Return to the authoring environment, and open the Actions panel.
About dot syntax and target paths 85
6. Type the following ActionScript after the code you added in step 3:
rotateClip.loadMovie("http://www.helpexamples.com/flash/images/
image1.jpg");
This code loads an image into the rotateClip movie clip that you created with code. You’re targeting the rotateClip instance with ActionScript.
7. Select Control > Test Movie to test your document.
Now you should see an image on the Stage that rotates 50º clockwise.
You can also target or identify parts of SWF files that you load into a base SWF file.
To identify a loaded SWF file:
Use _levelX, where X is the level number specified in the loadMovie() function that
loaded the SWF file.
For example, a SWF file loaded into level 99 has the target path following example, you load a SWF file into level 99 and set its visibility to
//Load the SWF onto level 99. loadMovieNum("contents.swf", 99); //Set the visibility of level 99 to false. loaderClip.onEnterFrame = function(){
_level99._visible = false;
};
TIP
It’s generally a good idea to avoid using levels if you can load content into movie clips at different depths instead. Using the enables you to create new movie clip instances on the Stage dynamically without having to check whether there is already an instance at a particular depth.
MovieClip.getNextHighestDepth() method
_level99. In the
false:
Setting variables using a path
You can set variables for instances that you nest inside of other instances. For example, if you want to set a variable for a form that’s inside another form, you can use the following code. The instance submitBtn is inside of
this.formClip.submitBtn.mouseOver = true;
You can express a method or property of a particular object (such as a movie clip or text field) using this pattern. For example, the property of an object would be
myClip._alpha = 50;
86 Syntax and Language Fundamentals
formClip on the main timeline:

About scope and targeting

When you nest instances, the movie clip that nests a second movie clip is known as the parent to the nested instance. The nested instance is known as the child instance. The main Stage and main timeline are essentially a movie clip themselves, and can therefore be targeted as such. For more information on scope, see “About variables and scope” on page 60.
You can target parent instances and parent timelines using ActionScript. When you want to target the current timeline, you use the clip called myClip that's on the current main timeline, you would use
this.myClip.
Optionally, you can drop the this keyword, and just use
myClip
You might choose to add the this keyword for readability and consistency. For more information on recommended coding practices, see Chapter 17, “Best Practices and Coding
Conventions for ActionScript 2.0,” on page 665.
If you trace the movie clip, for either snippet above you see panel. However, if you have ActionScript that’s inside the myClip movie clip but you want to target the main timeline, target the parent of the movie clip (which is the main Stage). Double-click a movie clip, and place the following ActionScript on the movie clip’s timeline:
trace("me: " + this); trace("my parent: " + this._parent);
Test the SWF file, and you’ll see the following message in the Output panel:
me: _level0.myClip my parent: _level0
This indicates you targeted the main timeline. You can use parent to create a relative path to an object. For example, if the movie clip clip animalClip, the following statement on the instance dogClip tells animalClip to stop animating:
this._parent.stop();
If you're familiar with Flash and ActionScript, you’ve probably noticed people using the _
root scope. The _root scope generally refers to the main timeline of the current Flash
document. You should avoid using the _ use relative target paths instead of
If you use
_root in your code, you can encounter errors if you load the SWF file into another
Flash document. When the SWF file loads into a different SWF file, might point to the root scope of the SWF file it loads into, instead of referring to its own root as you intend it to. This can lead to unpredictable results, or break functionality altogether.
this keyword. For example, when you target a movie
_level0.myClip in the Output
dogClip is nested inside the animating movie
root scope unless it’s absolutely necessary. You can
_root.
_root in the loaded file
About dot syntax and target paths 87

Using the Target Path button

Sometimes it takes some time to figure out what a given target path is, or what target path you need for a piece of code. If you target an instance you have on the Stage, you can use the Target Path button to determine what the path is to that instance.
To use the Target Path button:
1. Open the Actions panel (Window > Actions) and click the Insert Target Path button. The
movie clips in your current document appear in a dialog box.
2. Select one of the instances from the list in the dialog box.
3. Click OK.
4. The target path for the selected instance appears in the Script pane.

About slash syntax

Slash syntax was used in Flash 3 and 4 to indicate the target path of a movie clip or variable. This syntax is supported by ActionScript 1.0 in Flash Player 7 and earlier, but it’s not supported in ActionScript 2.0 and Flash Player 7 or Flash Player 8.
Using slash syntax is not recommended unless you do not have another option, such as when you create content intended specifically for Flash Player 4 or Flash Lite 1.1 (and earlier) where you must use slash syntax. For more information on Flash Lite, see the Flash Lite
product page.

About language punctuators

There are several language punctuators in Flash. The most common type of punctuators are semicolons ( special meaning in the Flash language and helps define data types, terminate statements or structure ActionScript. The following sections discuss how to use the punctuators in your code.
For more information on language punctuators, see the following topics:
“Semicolons and colons” on page 89
“Curly braces” on page 90
“Parentheses” on page 93
“About literals” on page 94
“Abo u t co mme nts” o n pag e 95
88 Syntax and Language Fundamentals
;), colons (:), parentheses [()] and braces ({}). Each of these punctuators has a
For more information on the dot (.) operator and array access ([]) operators, see “Using dot
and array access operators” on page 145. For information on white space and code formatting,
see “Formatting ActionScript syntax” on page 697.

Semicolons and colons

ActionScript statements terminate with a semicolon (;) character, as demonstrated in the following two lines of code:
var myNum:Number = 50; myClip._alpha = myNum;
You can omit the semicolon character and the ActionScript compiler assumes that each line of code represents a single statement. However, it is good scripting practice to use semicolons because it makes your code more readable. When you click the Auto Format button in the Actions panel or Script window, trailing semicolons are appended to the end of your statements by default.
NOTE
Using a semicolon to terminate a statement allows you to place more than one statement on a single line, but doing so usually makes your code more difficult to read.
Another place you use semicolons is in
for loops. You use the semicolon to separate
parameters, as shown in the following example. The example loops from 0 to 9 and then displays each number in the Output panel:
var i:Number; for (i = 0; i < 10; i++) {
trace(i); // 0,1,...,9 }
You use colons (:) in your code to assign data types to your variables. To assign a specific data type to an item, specify its type using the
var keyword and post-colon syntax, as shown in the
following example:
// strict typing of variable or object var myNum:Number = 7; var myDate:Date = new Date(); // strict typing of parameters function welcome(firstName:String, myAge:Number) { } // strict typing of parameter and return value function square(num:Number):Number {
var squared:Number = num * num;
return squared; }
About language punctuators 89
You can declare the data type of objects based on built-in classes (Button, Date, MovieClip, and so on) and on classes and interfaces that you create. In the following snippet, you create a new object of the custom type Student:
var firstStudent:Student = new Student();
You can also specify that objects are of the Function or the Void data type. For more information on assigning data types, see Chapter 3, “Data and Data Types,” on page 35.

Curly braces

You group ActionScript events, class definitions, and functions into blocks using curly brace (
{}) punctuators. You put the opening brace on the same line as the declaration.
NOTE
You can also put the opening brace on the line that follows the declaration. Coding conventions recommend that you put the opening brace on the same line for consistency. For information on braces and code conventions, see Chapter 17, “Best
Practices and Coding Conventions for ActionScript 2.0,” on page 665.
Place braces around each statement when it is part of a control structure (such as
for), even if it contains only a single statement. This good practice helps you avoid errors in
if..else or
your ActionScript when you forget to add braces to your code. The following example shows code that is written using poor form:
var numUsers:Number; if (numUsers == 0) trace("no users found.");
Although this code validates, it is considered poor form because it lacks braces around the statements.
TIP
Braces are added to this statement if you click the Auto Format button.
In this case, if you add a second statement after the trace statement, the second statement executes regardless of whether the
numUsers variable equals 0, which can lead to unexpected
results. For this reason, add braces so the code looks like the following example:
var numUsers:Number; if (numUsers == 0) { trace("no users found"); }
90 Syntax and Language Fundamentals
In the following example, you create both an event listener object and a MovieClipLoader instance.
var imgUrl:String = "http://www.helpexamples.com/flash/images/image1.jpg"; this.createEmptyMovieClip("img_mc", 100); var mclListener:Object = new Object(); mclListener.onLoadStart = function() {
trace("starting"); }; mclListener.onLoadInit = function(target_mc:MovieClip):Void {
trace("success"); }; mclListener.onLoadError = function(target_mc:MovieClip):Void {
trace("failure"); }; var myClipl:MovieClipLoader = new MovieClipLoader(); myClipl.addListener(mclListener); myClipl.loadClip(imgUrl, img_mc);
The next example displays a simple class file that could be used to create a Student object. You learn more about class files in Chapter 6, “Classes,” on page 187.
To use curly braces in an ActionScript file:
1. Select File > New and then select ActionScript File.
2. Select File > Save As and save the new document as Student.as.
3. Add the following ActionScript to the AS file.
// Student.as class Student {
private var _id:String; private var _firstName:String; private var _middleName:String; private var _lastName:String;
public function Student(id:String, firstName:String, middleName:String, lastName:String) {
this._id = id; this._firstName = firstName; this._middleName = middleName;
this._lastName = lastName; } public function get firstName():String {
return this._firstName; } public function set firstName(value:String):Void {
this._firstName = value; } // ...
}
About language punctuators 91
4. Save the class file.
5. Select File > New and click Flash Document to create a new FLA file.
6. Save the new FLA file as student_test.fla.
7. Type the following ActionScript on Frame 1 of the main Timeline:
// student_test.fla import Student; var firstStudent:Student = new Student("cst94121", "John", "H.", "Doe"); trace(firstStudent.firstName); // John firstStudent.firstName = "Craig"; trace(firstStudent.firstName); // Craig
Select File > Save to save the changes to student_test.fla.
8.
9. Select Control > Test Movie to test the FLA and AS files.
The next example demonstrates how curly braces are used when you work with functions.
To use curly braces with functions:
1. Select File > New and select Flash Document to create a new FLA file.
2. Select File > Save As and name the new file checkform.fla.
3. Drag an instance of the Label component from the Components panel onto the Stage.
4. Open the Property inspector (Window > Properties > Properties) and with the Label
component instance selected, type an instance name of status_lbl into the Instance Name text box.
5. Type 200 into the W (width) text box to resize the component to 200 pixels wide.
6. Drag an instance of the TextInput component onto the Stage and give it an instance name
of firstName_ti.
7. Drag an instance of the Button component onto the Stage and give it an instance name of
submit_button.
8. Select Frame 1 of the Timeline, and add the following ActionScript into the Actions panel:
function checkForm():Boolean {
status_lbl.text = ""; if (firstName_ti.text.length == 0) {
status_lbl.text = "Please enter a first name.";
return false; } return true;
} function clickListener(evt_obj:Object):Void {
var success:Boolean = checkForm();
}; submit_button.addEventListener("click", clickListener);
92 Syntax and Language Fundamentals
9. Select File > Save to save the Flash document.
10. Select Control > Test Movie to test the code in the authoring environment.
In the SWF file, an error message is displayed if you click the Button instance on the Stage when you do not have text in the
firstName_ti TextInput component. This error
appears in the Label component and informs users that they need to enter a first name.
The next example using curly braces shows how to create and define properties within an object. In this example, properties are defined in the object by specifying the variable names within the curly brace (
var myObject:Object = {id:"cst94121", firstName:"John", middleName:"H.",
lastName:"Doe"}; var i:String; for (i in myObject) {
trace(i + ": " + myObject[i]); } /*
id: cst94121
firstName: John
middleName: H.
lastName: Doe */
{}) punctuators:
You can also use empty curly braces as a syntax shortcut for the new Object() function. For example, the following code creates an empty Object instance:
var myObject:Object = {};
TIP
Remember to make sure each opening curly brace has a matching closing brace.

Parentheses

When you define a function in ActionScript, you place parameters inside parentheses [()] punctuators, as shown in the following lines of code:
function myFunction(myName:String, myAge:Number, happy:Boolean):Void { // Your code goes here. }
When you call a function, you also include any of the parameters you pass to the function in parentheses, as shown in the following example:
myFunction("Carl", 78, true);
You can use parentheses to override the ActionScript order of precedence or to make your ActionScript statements easier to read. This means you can change the order in which values are computed by placing brackets around certain values, as seen in the following example:
var computedValue:Number = (circleClip._x + 20) * 0.8;
About language punctuators 93
Because of order of precedence, if you didn’t use parentheses or use two separate statements, the multiplication would be computed first, meaning that the first operation would be 20 *
0.8. The result, 16, would then be added to the current value of circleClip._x and finally assigned to the
computedValue variable.
If you don’t use parentheses, you must add a statement to evaluate the expression, as shown in the following example:
var tempValue:Number = circleClip._x + 20; var computedValue:Number = tempValue * 0.8;
As with brackets and braces, you need to make sure each opening parentheses has a closing parentheses.

About literals

A literal is a value that appears directly in your code. Literals are constant (unchanging) values within your Flash documents. Examples of a literal include string
“foo”.
The following examples are all literals:
17 "hello"
-3
9.4 null undefined true false
Literals can also be grouped to form compound literals. Array literals are enclosed in bracket punctuators (
[]) and use the comma punctuator (,) to separate array elements. An array
literal can be used to initialize an array. The following examples show two arrays that are initialized using array literals. You can use the
new statement and pass the compound literal as
a parameter to the Array class constructor, but you can also assign literal values directly when instantiating instances of any built-in ActionScript class.
// using new statement var myStrings:Array = new Array("alpha", "beta", "gamma"); var myNums:Array = new Array(1, 2, 3, 5, 8);
true, false, 0, 1, 52, or even the
// assigning literal directly var myStrings:Array = ["alpha", "beta", "gamma"]; var myNums:Array = [1, 2, 3, 5, 8];
94 Syntax and Language Fundamentals
Literals can also be used to initialize a generic object. A generic object is an instance of the Object class. Object literals are enclosed in curly braces ( (
,) to separate object properties. Each property is declared with the colon punctuator (:),
{}) and use the comma punctuator
which separates the name of the property from the value of the property.
You can create a generic object using the
new statement and pass the object literal as a
parameter to the Object class constructor, or you can assign the object literal directly to the instance you are declaring. The following example creates a new generic object and initializes the object with three properties,
propA, propB, and propC, each with values set to 1, 2, and 3,
respectively.
// using new statement var myObject:Object = new Object({propA:1, propB:2, propC:3});
// assigning literal directly var myObject:Object = {propA:1, propB:2, propC:3};
Do not confuse a string literal with a String object. In the following example, the first line of code creates the string literal
secondStr:
var firstStr:String = "foo" var secondStr:String = new String("foo")
firstStr, and the second line of code creates the String object
Use string literals unless you specifically need to use a String object for better performance. For more information on strings, see “About strings and the String class” on page 411.

About comments

Comments are a way of annotating your code with plain-English descriptions that do not get evaluated by the compiler. You can use comments within your code to describe what the code is doing or to describe which data returns to the document. Using comments can help you remember important coding decisions, and it can be helpful to anyone else who reads your code. Comments must clearly explain the intent of the code and not just translate the code. If something is not readily obvious in the code, you should add comments to it.
Using comments to add notes to scripts is highly recommended. Comments document the decisions you make in the code, answering both how and why. They make ActionScript easier to understand. For example, you might describe a work-around in comments. Therefore, you or another developer can easily find sections of code to update or fix. Or, if the issue is fixed or improved in a future version of Flash or Flash Player, you could improve the ActionScript by removing the work-around.
About language punctuators 95
Avoid using cluttered comments. An example of cluttered comments is a line of equal signs (=) or asterisks (*) used to create a block or separation around your comments. Instead, use white space to separate your comments from the ActionScript. If you format your ActionScript using the Auto Format button in the Actions panel or Script window, this removes the white space. Remember to add white space back into your code, or use single comment lines (
//) to maintain spacing; these lines are easier to remove after you format your
code than trying to determine where white space once was.
Before you deploy your project, remove any superfluous comments from the code, such as “define the x and y variables” or other comments that are immediately obvious to other developers. If you find that you have many extra comments in the ActionScript, consider whether you need to rewrite some of the code. If you need to include many comments about how the code works, it is usually a sign that the ActionScript is inelegant and not intuitive.
When you enable syntax coloring, comments are gray by default. Comments can be any length without affecting the size of the exported file, and they do not need to follow rules for ActionScript syntax or keywords.
NOTE
Using comments is most important in ActionScript that is intended to teach an audience. Add comments to your code if you are creating sample applications for the purpose of teaching Flash or if you are writing articles or tutorials on ActionScript.
Single-line comments
You use single-line comments to add a comment to a single line in your code. You might comment out a single line of code, or add a short description of what a piece of code accomplishes. To indicate that a line or portion of a line is a comment, precede the comment with two forward slashes (//), as shown in the following code:
// The following sets a local variable for age. var myAge:Number = 26;
Single-line comments are typically used to explain a small code snippet. You can use single­line comments for any short comments that fit on a single line. The following example includes a single-line comment:
while (condition) {
// handle condition with statements }
96 Syntax and Language Fundamentals
Multiline comments
Use multiline comments, also called block comments, for comments that are several lines in length. Developers commonly use multiline comments to describe files, data structures, methods, and descriptions of files. They are usually placed at the beginning of a file and before or within a method.
To create a comment block, place end of the comment block. This technique lets you create lengthy comments without adding // at the beginning of each line. Using // for numerous sequential lines can lead to some problems when you modify the comments.
The format for a multiline comment is as follows.
/*
The following ActionScript initializes variables used in the main and
sub-menu systems. Variables are used to track what options are clicked. */
TIP
If you place the comment characters (/* and */) on separate lines at the beginning and end of the comment, you can easily comment them out by placing double slash characters (//) in front of them (for example, ///* and //*/). These let you quickly and easily comment and uncomment your code.
By placing large chunks of script in a comment block, called commenting out a portion of your script, you can test specific parts of a script. For example, when the following script runs, none of the code in the comment block executes:
// The following code runs. var x:Number = 15; var y:Number = 20;
/* at the beginning of the commented lines and */ at the
// The following code is commented out and will not run. /* // create new Date object var myDate:Date = new Date(); var currentMonth:Number = myDate.getMonth(); // convert month number to month name var monthName:String = calcMonth(currentMonth); var year:Number = myDate.getFullYear(); var currentDate:Number = myDate.getDate(); */
// The code below runs. var namePrefix:String = "My name is"; var age:Number = 20;
TIP
It’s good practice to place a blank line before a block comment.
About language punctuators 97
Trailing comments
You use trailing comments to add a comment on the same line as your code. These comments appear on the same line as your ActionScript code. Developers commonly use trailing comments to indicate what a variable contains or to describe or note the value that returns from a line of ActionScript. Format trailing comments as follows:
var myAge:Number = 26; // variable for my age trace(myAge); // 26
Space the comments to the right so readers can distinguish them from the code. Try to have the comments line up with each other, if possible, as shown in the following code.
var myAge:Number = 28; // my age var myCountry:String = "Canada"; // my country var myCoffee:String = "Hortons"; // my coffee preference
If you use autoformatting (click the Auto Format button in the Actions panel), trailing comments move to the next line. Add these comments after you format your code, or you must modify their placement after using the Auto Format button.
Comments inside classes
You use comments in your classes and interfaces to document them to help developers understand the contents of your class. You might start all your class files with a comment that provides the class name, its version number, the date, and your copyright. For example, you might create documentation for your class that is similar to the following comment:
/** Pelican class version 1.2 10/10/2005 copyright Adobe Systems Incorporated */
Use block comments to describe files, data structures, methods, and descriptions of files. They are usually placed at the beginning of a file and before or within a method.
There are two kinds of comments in a typical class or interface file: documentation comments and implementation comments. Documentation comments are used to describe the code’s specifications and do not describe the implementation. You use documentation comments to describe interfaces, classes, methods, and constructors. Implementation comments are used to comment out code or to comment on the implementation of particular sections of code.
98 Syntax and Language Fundamentals
Include one documentation comment per class, interface, or member, and place it directly before the declaration. If you have additional information to document that does not fit into the documentation comments, use implementation comments (in the format of block comments or single-line comments). Implementation comments directly follow the declaration.
The two kinds of comments use slightly different delimiters. Documentation comments are delimited with
TIP
Don’t include comments that do not directly relate to the class being read. For example, do not include comments that describe the corresponding package.
/** and */, and implementation comments are delimited with /* and */.
You can also use single-line comments, block comments, and trailing comments in class files. For more information on these kinds of comments, see the following sections:
“Single-line comments” on page 96
“Multiline comments” on page 97
“Trailing comments” on page 98

About constants and keywords

Constants and keywords are the backbone of ActionScript syntax. Constants are properties with a fixed value that cannot be altered, so they are values that don’t change throughout an application.
Flash includes several predefined constants, which can help simplify application development. An example of constants can be found in the Key class, which includes many properties, such
Key.ENTER or Key.PGDN. If you rely on constants, you never have to remember that the key
as code values for the Enter and Page Down keys are 13 and 34. Using constant values not only makes development and debugging easier, but it also makes your code easier to read by your fellow developers.
Keywords in ActionScript are used to perform specific kinds of actions. They are also reserved words because of this, so you can’t use them as identifiers (such as variable, function, or label names). Examples of some reserved keywords are
For more information on constants and keywords, see the following topics:
“Using constants” on page 100
“About keywords” on page 102
“About reserved words” on page 103
if, else, this, function, and return.
About constants and keywords 99
For more information on objects and properties, see “Object data type” on page 42. For a list of constants in the language (such as
false and NaN), see the ActionScript Language Elements
> Constants category in the ActionScript 2.0 Language Reference.

Using constants

Constants are properties with a fixed value that cannot be altered; in other words, they are values that don’t change throughout an application. The ActionScript language contains many predefined constants. For example, the constants properties of the Key class and refer to keyboard keys. The constant same meaning: it indicates the Tab key on a keyboard. Constants are useful for comparing values and for using values in your application that do not change.
To test whether the user is pressing the Enter key, you could use the following statement:
var keyListener:Object = new Object(); keyListener.onKeyDown = function() {
if (Key.getCode() == Key.ENTER) {
trace("Are you ready to play?");
} }; Key.addListener(keyListener);
For the previous ActionScript to work, it may be necessary to disable keyboard shortcuts in the authoring environment. Select Control > Test Movie from the main menu, then while previewing the SWF file in the player, select Control > Disable Keyboard Shortcuts from the SWF file’s preview window.
In Flash there is no way to create your own constant values except when you create your own custom classes with private member variables. You cannot create a “read-only” variable within Flash.
Variables should be lowercase or mixed-case letters; however, constants (variables that do not change) should be uppercase. Separate words with underscores, as the following ActionScript shows:
var BASE_URL:String = "http://www.adobe.com"; //constant var MAX_WIDTH:Number = 10; //constant
Write static constants in uppercase, and separate words with an underscore. Do not directly code numerical constants unless the constant is 1, 0, or -1, which you might use in a as a counter value.
You can use constants for situations in which you need to refer to a property whose value never changes. This helps you find typographical mistakes in your code that you might not find if you use literals. It also lets you change the value in a single place. For more information on literals, see “About literals” on page 94.
BACKSPACE, ENTER, SPACE, and TAB are
Key.TAB always has the
for loop
100 Syntax and Language Fundamentals
Loading...