Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

actionscript 3: how to pass array by reference to function, and have that function update it?

ActionScript 3 passes an array by reference, by default. I must be making a rookie mistake. Here's a snapshot of my code:

private function testFunc():void {
    var testArray:Array=new Array();
    myFunction(testArray);
    trace(testArray); // []; length=0
}

private function myFunction(tArray:Array):void {
    tArray = myOtherFunction();
    trace(tArray); // 0, 1, 2; length=3
}

private function myOtherFunction():Array {
    var x:Array=new Array;
    for (var i:int=0; i<3; i++)
       x[i]=i;
    return x;
}

I can see that tArray is correct, but testArray is always empty. Any idea how to make testArray equal tArray? Thanks in advance.

http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000049.html

UPDATE:

For what it's worth, I found the following change (hack) to work:

private function myFunction(tArray:Array):void {
    var Z:Array=new Array;
    Z = myOtherFunction();
    for (var i:int=0; i<Z.length; i++)
        tArray[i]=Z[i];
}

Georgii's solution is better design though.

like image 503
ggkmath Avatar asked Dec 01 '25 04:12

ggkmath


1 Answers

When you pass testArray as a parameter to myFunction, its reference is copied and assigned to local reference tArray, such that inside of myFunction tArray points to the same object as testArray, but is in fact a different reference. That is why when you change tArray reference, testArray itself does not change.

private function testFunc():void {
    var testArray:Array=new Array(); 
    // testArray is a local variable, 
    // its value is a reference to an Array object
    myFunction(testArray);
    trace(testArray); // []; length=0
}

private function myFunction(tArray:Array):void {
    // tArray is a local variable, which value equals to testArray
    tArray = myOtherFunction(); 
    // now you changed it and tArray no longer points to the old array
    // however testArray inside of testFunc stays the same
    trace(tArray); // 0, 1, 2; length=3
}

What you probably want is:

private function testFunc():void {
    var testArray:Array=new Array();
    testArray = myFunction(testArray);
    trace(testArray); // 0, 1, 2; length=3
}

private function myFunction(tArray:Array):Array {
    // do what you want with tArray
    tArray = myOtherFunction();
    trace(tArray); // 0, 1, 2; length=3
    // return new value of the tArray
    return tArray;
}

private function myOtherFunction():Array {
    var x:Array=new Array;
    for (var i:int=0; i<3; i++)
       x[i]=i;
    return x;
}
like image 113
Georgii Oleinikov Avatar answered Dec 02 '25 19:12

Georgii Oleinikov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!