Unrolling var args in AS3
actionscript-3, variadic-functions
Solution
The apply() method on all functions lets you pass in the arguments in an array instead of the "normal" way.
package {
import flash.display.Sprite;
public class Foo extends Sprite {
public function Foo() {
var args:Array = ["a", "b", "c"];
// "normal" call
varArgsFunc(args);
// what you wanted:
varArgsFunc.apply(null, args);
}
public function varArgsFunc(...args):Array {
trace("got", args);
}
}
}
Problem
I'm wondering if there is some way to unpack a variable length argument list in AS3. Take for example this function: ``` public function varArgsFunc(amount:int, ...args):Array { if (amount == 3) { return args } else { return varArgsFunc(++amount, args) } } ``` If I call this: ``` var result:Array = varArgsFunc(0, []) ``` result now contains a nested set of arrays: ``` [[[[]]]] ``` The problem here is that the args parameter is treated as an array. So if i pass it onto a function with a variable argument list, it will be treated as a single argument. In Scala there is the :_* operator that tells the compiler to break apart a list into a list of parameters: ``` var list:Array = ['A', 'B', 'C'] // now imagine we have this class, but I would like to pass each list element // in as a separate argument class Tuple { public function Tuple(...elements) { // code } } // if you do this, the list will become be passed as the first argument new Tuple(list) // in scala you can use the :_* operator to expand the list new Tuple(list :_*) // so the :_* operator essentially does this new Tuple(list[0], list[1], list[2]) ``` I would like to know if a technique/operator exists in AS3 to expand an array into an argument list.