Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the cleanest way to simulate pass-by-reference in Actionscript 3.0?

Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this?

For example, is there a clean way to implement swap( intA, intB ) in Actionscript?

like image 735
Matt W Avatar asked Sep 08 '08 03:09

Matt W


4 Answers

I Believe the best you can do is pass a container object as an argument to a function and change the values of some properties in that object:

function swapAB(aValuesContainer:Object):void
{
    if (!(aValuesContainer.hasOwnProperty("a") && aValuesContainer.hasOwnProperty("b")))
        throw new ArgumentError("aValuesContainer must have properties a and b");

    var tempValue:int = aValuesContainer["a"];
    aValuesContainer["a"] = aValuesContainer["b"];
    aValuesContainer["b"] = tempValue;
}
var ints:Object = {a:13, b:25};
swapAB(ints);
like image 137
hasseg Avatar answered Nov 09 '22 06:11

hasseg


I suppose an alternative would be somewhere defining this sort of thing ...

public class Reference {
    public var value:*;
}

Then use functions that take some number of Reference arguments to act as "pointers" if you're really just looking for "out" parameters and either initialize them on the way in or not and your swap would become:

function swap(Reference a, Reference b) {
    var tmp:* = a.value;
    a.value = b.value;
    b.value = tmp;
}

And you could always go nuts and define specific IntReference, StringReference, etc.

like image 30
imaginaryboy Avatar answered Nov 09 '22 05:11

imaginaryboy


This is nitpicking, but int, String, Number and the others are passed by reference, it's just that they are immutable. Of course, the effect is the same as if they were passed by value.

like image 4
Theo Avatar answered Nov 09 '22 05:11

Theo


You could also use a wrapper instead of int:

public class Integer
{
    public var value:int;

    public function Integer(value:int)
    {
        this.value = value;
    }
}

Of course, this would be more useful if you could use operator overloading...

like image 3
Andres Avatar answered Nov 09 '22 05:11

Andres