Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actionscript 3 - Reference vs. Value

I thought I had references in AS3 figured out, but the following behavior puzzles me:

// declarations for named individual reference later on
var myAmbientSound:Sound;
var myAmbientSoundLocation:String = "http://ambient_sound_location";

var myPeriodicSound:Sound;
var myPeriodicSoundLocation:String = "http://periodic_sound_location";

var myOccasionalSound:Sound;
var myOccasionalSoundLocation:String = "http://occasional_sound_location";

// for iterating through initialization routines
var mySoundArray:Array = [myAmbientSound, myPeriodicSound, myOccasionalSound];
var mySoundLocation:Array = [myAmbientSoundLocation, myPeriodicSoundLocation, myOccasionalSoundLocation];

// iterate through the array and initialize
for(var i:int = 0; i < mySoundArray.length; i++) {
    mySoundArray[i] = new Sound();
    mySoundArray[i].load(new URLRequest(mySoundLocation[i]));
}

At this point, I'd think that mySoundArray[0] would reference the same object as myAmbientSound; however, accessing myAmbientSound throws a null pointer exception, while mySoundArray[0] works as expected and references a Sound object. What am I misunderstanding here?

like image 835
justinbach Avatar asked Dec 13 '22 23:12

justinbach


1 Answers

It is more like java reference variables than C pointers.

var myAmbientSound:Sound;
var myPeriodicSound:Sound;
var myOccasionalSound:Sound;
//these variables are not initialized and hence contain null values

Now you create an array containing the current values (null) of these variables

var mySoundArray:Array = [myAmbientSound, myPeriodicSound, myOccasionalSound];

The array now contains three nulls [null, null, null], and not three pointers to Sound objects as you expect it to contain.

Now when you call mySoundArray[0] = new Sound(); a new Sound object is created and its address is assigned to the first location of the array - it doesn't modify the myAmbientSound variable.

like image 92
Amarghosh Avatar answered Dec 21 '22 09:12

Amarghosh