views:

351

answers:

3

i'm confused with the term "global" in AS3. within my main controller class, i've defined a variable (myNum) which i would like to access throughout all class .as files within the same package.

//Controller class

package myApp
{
public var myNum:int = 24; //try to access myNum in mySprite class

public class Main extends Sprite
    {
    }
}

______________________________

//Object class

package myApp
{
public class mySprite extends Sprite
    {
    trace (myNum);
    }
}

the above code returns the following error:

5006: An ActionScript file can not have more than one externally visible definition

what is the proper way to set up a list of global variables that can be accessed throughout the entire scope of a package?

+2  A: 

Your compilation problem is because

public var myNum:int = 24

needs to be defined within the Main class, not outside of it.

If you want to make it a global variable, one way of doing that is declaring it static like so:

package myApp
{

public class Main extends Sprite
    {
    public static var myNum:int = 24; //try to access myNum in mySprite class
    }
}

and then accessing it from other classes like so:

import myApp.Main; //don't need this line if accessing from same package 
trace(Main.myNum);
teehoo
A: 

A static class with static variables.

Tegeril
+1  A: 

Static variables could accomplish this.

You can declare a variable as internal static so that other classes in the same package can use it. Or you can declare it as public static so that all classes in your project can use it, even if they're in a different package.

In the code below, myNum1 is accessible by classes in the same package, whereas myNum2 can be accessed from anywhere.

package myApp
{
    public class Main extends Sprite
    {
        internal static var myNum1:int = 1;
        public static var myNum2:int = 2;
    }
}

Example of access from the same package:

package myApp
{
    public class ClassInSamePackage
    {
        public function doSomething():void
        {
            trace(Main.myNum1); // traces 1
            trace(Main.myNum2); // traces 2
        }
    }
}

Example of access from a different package:

package otherApp
{
    import myApp;

    public class ClassInDifferentPackage
    {
        public function doSomething():void
        {
            trace(Main.myNum1); // error!
            trace(Main.myNum2); // traces 2
        }
    }
}

Internal is actually the default access modifier in AS3, so writing internal static var is the same as writing static var. But it is probably better to write internal static var anyway just to be clear.

PS It's unclear from your example whether you've placed the two classes in one or two files. If you've placed them both in only one file, bear in mind that one AS file can only contain one class.

danyal