Passing a list of arbitrary function arguments in Haxe

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

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

Then I can call the function passing the array:

 foo.apply(this, argsArray); 

I would like to call a function with arguments of an unknown type and quantity. Is this possible in Haxe?

+6
source share
3 answers

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

If the last argument of the macro is of type Array<Expr> macro takes an arbitrary number of additional arguments available from this 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; } } 
+6
source

You can 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]]); } } 
+4
source

Just add to this, if you are describing extern for an external JavaScript library (or Python, Lua, or any target language that supports the rest parameter , for example ...rest ), there is a specific Haxe type, haxe.extern.Rest , to express this .

Here is an example showing that the JavaScript function Math.max processes variables: http://try.haxe.org/#4607C

 class Test { static function main() { trace("JS Math.max takes varargs:"); trace(MyMath.max(1,2,3,4)); // 4 trace(MyMath.max(5,6)); // 6 } } @:native("Math") extern class MyMath { static function max(a:Float, b:Float, rest:haxe.extern.Rest<Float>):Float; } 

Please note that the standard Haxe library does not define Math.max with Rest , as its goal is cross-platform compatibility.

+3
source

Source: https://habr.com/ru/post/1212872/


All Articles