Sunday, May 1, 2011

Pass By Reference in AS3

Turns out, you can't do it.

Example:

var A1:Array = [1,2,3,4];
function theFunction(someArray:Array){
var otherArray:Array = [555,555,555];
someArray = otherArray;
}//[x]
theFunction(A1);
trace("A1==" + A1);

output:
A1==[1,2,3,4]


Now, you are probably saying:
[1]: Why do this?
[2]: Why not use return value?

I wanted to make a function called: removeReferences.
Usage: removeReferences(theArray,theObject);
It would look for references of theObject in theArray and
set those references to null. Then the next pass would create a new
array where the null references would not be included.

Basically....
My function still works.... But it has to be called as such:
theArray = removeReferences(theArray,theObject);

Which to me is ugly ugly syntax.
It is akin to saying: theArray = theArray.push(theObject);

Unfortunately, all the other workarounds are even uglier...

2 comments:

  1. I myself have recently come across this issue but you can use the following as well

    function theFunction(someArray:Array){
    someArray[0] = 555;
    someArray[1] = 555;
    someArray[2] = 555;
    }

    ReplyDelete
  2. Ah. So it works as long as you explicitly reference the elements, but not the whole array?
    I shall keep this one in mind. :)

    ReplyDelete