Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actionscript3: Does variable exist?

I'm a little bit new to Actionscript, but I can't figure this one out. I've done a lot of searching on this topic and haven't found a clear answer. I've tried the following solutions that people posted online but none of them work.

All the following solutions give the error: 1120: Access of undefined property myVariable

Suggestion #1:

try {
     trace(myVariable); }
catch {
     trace("your variable doesn't exist"); }

Suggestion #2:

if (myVariable) {
     trace("your variable exists!!"); }
else {
     trace("it doesn't exist"); }

Suggestion #3:

if ( myVariable == null )
     trace("your variable doesn't exist");

Suggestion #4:

if ( myVariable == undefined )
     trace("your variable doesn't exist");

Like I said, I've found many forums posts and stuff online that give the above suggestions saying they will work, but they all seem to be giving me that same 1120: Access of undefined property myVariable error.

By the way, in case you are wondering why I would need to check if a variable exists or not, I'm planning on passing variables to the SWF in its URL, so I need to make sure the proper variables exist and handle the code properly if they are not passed in.


Thanks for the quick reply. Still not really working. The scope of the variable is just on the top/root level of the script. Basically, I start a new flash file, on the first frame I add the following action:

// to check for this.myVariable
if ( this.hasOwnProperty( "myVariable" ) ) {
     trace("myVariable exists");
}
else
{
     //Variable doesn't exist, so declare it now
     trace("declaring variable now...");
     var myVariable = "Default Value";
}

trace(myVariable);

When I run the flash file, I get this output:

myVariable exists
undefined

I was expecting this:

declaring variable now...
Default Value
like image 482
Jake Wilson Avatar asked Sep 27 '09 05:09

Jake Wilson


1 Answers

LiraNuna's answer is definitely the right way to access loader parameters. However, to answer the question of how to check for the existence of variables (for posterity), this is done with the hasOwnProperty() method, which exists on all objects:

// to check for this.myVariable
if ( this.hasOwnProperty( "myVariable" ) ) {
    trace("myVariable exists");
} else {
    //Variable doesn't exist, so declare it now
    trace("declaring variable now...");
    this.myVariable = "Default Value";
}

trace( this.myVariable );

That should cover your situation. But I don't know of any way to check the existence of a variable the way you're trying to do, by merely making a reference directly to the variable. I believe you must refer to it through its scope.

like image 178
fenomas Avatar answered Oct 14 '22 08:10

fenomas