1
votes

I have an AS3 function that runs when a URLRequest fails. I need to be able to use this function to assign global variables that I can then check against using other functions. How do I assign global variables inside of a function?

Thanks!

Edit:This is the variable (soundFile2Exist) I am trying to get outside of my function:

function onIOError(e:IOErrorEvent):void 
{

    var soundFile2exist = null;
    trace (soundFile2exist);
}

I am not using my code inside of a packge. Is there still a way to do this?

function playMusic(evt:MouseEvent):void
{
    channel = myMusic.play(songPosition);
    if (soundFile2exist != null) {
          channel2 = myMusic2.play(channel.position);
    }
    myTimer.start();
    btnPlay.mouseEnabled = false;
    trace (soundFile2exist);

}
2
I am strongly opposed to the entire premise of this question, that you would want to pass data between functions using global variables.jhocking
What do you mean? I may have mis-phrased my question.user547794
There are many ways of sharing data between functions that do not involve global variables. Global variables are pretty much the worst way of accomplishing that task.jhocking
How do I share data between functions?user547794
Your statement that "I am not using my code inside of a package" suggests to me that you don't know how to do object-oriented programming. AS3 is a strongly object-oriented language, so I suggest learning about that.jhocking

2 Answers

4
votes

If your code is "not in a package" (like in a frame script on a timeline), any variables you declare on the same level, same scope, as your functions will be accessible to the functions in that scope, so you could do something in the lines of this:

var soundFile2exist;

function onIOError(e:IOErrorEvent):void {
   soundFile2exist = null;
}

function otherFunction():void {
   trace (soundFile2exist);
}

In other situations, static variables of a class can be used in place of global variables.

1
votes

The most common approach is to create a Singleton class which you can then reference from anywhere. This basically sets up a class where the only way to get access to an instance of that class is via a controlled static method that returns one and only one instance. So whenever you say MySingleton.getInstance() you always end up with the same object.

Grant Skinner has a quick writeup of how to implement a Singleton in AS3: http://gskinner.com/blog/archives/2006/07/as3_singletons.html