Actionscript 3.0 swap
Is it possible to implement swapping routine in ActionScript 3.0 similar to C++ std::swap? I mean something like
public static function Swap(var a, var b):void
{
var c = a;
a = b;
b = c;
}
and then
var a:int = 3;
var b:int = 5;
Swap(a,b);
trace(a, " ", b); // there must be 5 3
It 开发者_C百科doesn't work "as is" for integers because they're passed by value, not ref into the Swap routine.
Unfortunately you can't implement a swap in this way, because ActionScript 3, Java, and many other languages pass primitives and object references by value. That link will give you the details, but basically this means that the references inside the function aren't the same as the references outside the function (even though they indeed refer to the same object). Therefore, fiddling with the parameter references in the function has no effect outside the function. You're forced to do the swap inline.
If you really needed some swap behavior in a function, you'd have to wrap the parameters in another object, and then you can change the inner reference:
public static function Swap(var a, var b)
{
var c = a.value;
a.value = b.value;
b.value = c;
}
Sadly, Actionscript always pass primitives by value, and always pass objects by reference¹ (someone correct me if I'm wrong).
What you can do is wrap your primitive into a object.
var A:Object = {"value":3};
var B:Object = {"value":5};
Swap(A, B);
trace(A.value, B.value);
function Swap(a:Object, b:Object):void
{
var temp:Object = a.value;
a.value = int(b.value);
b.value = int(temp);
}
I know... This is ugly and won't fit in most of the cases...
¹ In fact, it isn't true, as the references are different but points to the same object, contrary to primitives, that the references points to different primitive values.
If you can postprocess your SWF you can use Apparat tools
to create a Macro
: http://code.google.com/p/apparat/wiki/MacroExpansion
it even already exists a swap method into the BitMacro
:
http://www.google.com/codesearch/p?hl=en#3GyOvBpuCbk/apparat-ersatz/src/main/as3/apparat/math/BitMacro.as&q=swap%20package:http://apparat%5C.googlecode%5C.com&sa=N&cd=3&ct=rc
精彩评论