Search code examples
actionscript-3clone

Duplicate a variable in AS3


I'm trying to swap two variables in ActionScript.

I tried using:

a = 42
b = 50

tempvar = a
a = b
b = tempvar

to switch, but this doesn't work because the variables still reference the original value, so if I set b = a, and then change a, b changes as well.

in ruby, you have clone(), but I don't know a similar method for AS3.

Help?


Solution

  • The following works fine. Surely you have not shown all your code?

    import flash.display.Sprite;
    public class SwapTest extends Sprite
    {
        public function SwapTest()
        {
            var a:int=42;
            var b:int=50;
            var temp:int=a;
            a=b;
            b=temp;
            trace("a="+a);
            trace("b="+b);
        }
    }
    

    Traces

    a=50
    b=42
    

    No clone required. Even the following untyped code, that more closely follows your example gives the same output:

            var a=42;
            var b=50;
            var temp=a;
            a=b;
            b=temp;
            trace("a="+a);
            trace("b="+b);
    

    How are you declaring a,b and tempVar? Is this timeline code?