98 Data and Data Types
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 */
3.
Select Frame 20 of the Timeline.
4. Select Insert > Timeline > Blank Keyframe.
5. With the new keyframe selected, type the following ActionScript into the Actions panel:
trace(myNum);
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
stop();
after the
trace() statement.
You must declare a timeline variable before trying to access it in a script. For example, if you
put the code
var myNum:Number = 15; in Frame 20, any scripts attached to a frame before
Frame 20 cannot access
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
myStr within a function named localScope,
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