views:

60

answers:

2

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?

+2  A: 
var tempvar:uint = new uint(a);
a = new uint(b);
b = tempvar;
Warren Young
+2  A: 

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?

spender