Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrolling var args in AS3

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.

like image 317
BefittingTheorem Avatar asked Sep 10 '09 07:09

BefittingTheorem


2 Answers

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);
        }

    }

}
like image 137
grapefrukt Avatar answered Nov 12 '22 19:11

grapefrukt


As a side note to this answer

The original question was not only passing the "unrolled" ...args using the super but to also pass a regular variable first

public function varArgsFunc(amount:int, ...args):Array

If this was the actual method being called the code would be

public function varArgsFunc(amount:int, ...args):Array
{  
  super.varArgsFunc.apply(this, [amount].concat(args));
}
like image 24
MonkeyMagiic Avatar answered Nov 12 '22 18:11

MonkeyMagiic