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?
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;
  }
}
                        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]]);
    }
}
                        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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With