Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 knowing how many arguments a function takes

Is there a way to know how many arguments an instance of Function can take in Flash? It would also be very useful to know if these arguments are optional or not.

For example :

public function foo() : void                               //would have 0 arguments
public function bar(arg1 : Boolean, arg2 : int) : void     //would have 2 arguments
public function jad(arg1 : Boolean, arg2 : int = 0) : void //would have 2 arguments with 1 being optional

Thanks

like image 644
Godfather Avatar asked Nov 24 '11 12:11

Godfather


1 Answers

Yes there is: use the Function.length property. I just checked the docs: it doesn't seem to be mentioned there though.

trace(foo.length); //0
trace(bar.length); //2
trace(jad.length); //2

Notice there are no braces () after the function name. You need a reference of the Function object; adding the braces would execute the function.

I do not know of a way to ascertain that one of the arguments is optional though.

EDIT

What about ...rest parameters?

function foo(...rest) {}
function bar(parameter0, parameter1, ...rest) {}

trace(foo.length); //0
trace(bar.length); //2

This makes sense since there is no way of knowing how many arguments will be passed. Note that within the function body you can know exactly how many arguments were passed, like so:

function foo(...rest) {
    trace(rest.length);
}

Thanks to @felipemaia for pointing that out.

like image 72
RIAstar Avatar answered Sep 18 '22 15:09

RIAstar