Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing list of arbitrary function arguments in Haxe

In ActionScript I can use ... in a function declaration so it accepts arbitrary arguments:

function foo(... args):void { trace(args.length); }

I can then call the function passing an array:

foo.apply(this, argsArray);

I'd like to call the function with arguments of unknown type and count. Is this possible in Haxe?

like image 890
meps Avatar asked Feb 07 '15 19:02

meps


3 Answers

According to the Haxe documentation, you can use a Rest argument:

If the final argument of a macro is of type Array<Expr> the macro accepts an arbitrary number of extra arguments which are available from that array:

import haxe.macro.Expr;

class Main {
  static public function main() {
    myMacro("foo", a, b, c);
  }

  macro static function myMacro(e1:Expr, extra:Array<Expr>) {
    for (e in extra) {
      trace(e);
    }
    return macro null;
  }
}
like image 94
user4541493 Avatar answered Oct 20 '22 08:10

user4541493


You could use Reflect.callMethod():

class Test {
    static function main() {
        var console = js.Browser.window.console;
        var fn = console.log;
        Reflect.callMethod(console, fn, [1, 2, "three", [4]]);
    }
}
like image 5
Andrew Avatar answered Oct 20 '22 10:10

Andrew


Starting with Haxe 4.2, Haxe will have native support for rest arguments:

function f(...args:Int) {
    for (arg in args) {
        trace(arg);
    }
}

f(1, 2, 3);

...args:Int is simply syntax sugar for rest:haxe.Rest<Int>. Only the last argument of a function can be a rest argument.

You can also use ... to "spread" an array when calling a function with a rest argument:

final array = [1, 2, 3];
f(...array);
like image 3
Gama11 Avatar answered Oct 20 '22 10:10

Gama11