Sunday, 13 February 2011

Passing Through Unknown Number of Parameters in Actionscript

Hi Readers,

It's probably a noob problem but for me it took some time to solve. Actionscript can handle unknown number of arguments in the function definition:


public function foo(...args):void {
}

In this case ...args is an Array. You can call this function with any amount of arguments, like:

foo(); // args = []
foo('bar'); // args = ['bar']
foo('bar', 1, new Object()); // args = ['bar', 1, -object instance-]

It's very handy a lot of times. But the problem is if you want to pass those arguments through more than one functions. Here you are a minimalist example:

package {
import flash.display.Sprite;
public class ArgSample extends Sprite {

public function ArgSample() {
this.bar(1, 2, 3);
}

public function bar(...args):void {
this.foo(args);
}

public function foo(...args):void {
trace('Number of parameters: ' + args.length);
}
}
}
You want to guess the results of foo? It's: "Number of parameters: 1". Why? Because in function bar() you pass variable args, which is an Array. And foo() will receive an Array with 1 element: [[1, 2, 3]] instead of [1, 2, 3].

So how we gonna solve this? Let's use the dynamic behavior of Actionsctipt. Functions has a well known method: apply. It can do a function call on an object with an array of parameters. See the changes:

package {
import flash.display.Sprite;
public class ArgSample extends Sprite {

public function ArgSample() {
this.bar(1, 2, 3);
}

public function bar(...args):void {
(this.foo as Function).apply(this, args);
}

public function foo(...args):void {
trace('Number of parameters: ' + args.length);
}
}
}
And now magically the result is: "Number of parameters: 3". In real life I'm using it when I create a NetConnection object for making remote function calls and I have to provide arguments.

Bests,
Peter

No comments:

Post a Comment