Haxe - variable number of arguments in SWC

Viewed 96

I am porting a library from AS3 to Haxe and I need to make a method accepting variable number of arguments. Target is a *.swc library.

My question relates to this one but none of the suggested solutions outputs a method with the required signature: someMethod(...params)

Instead, the produced method is: someMethod(params:*=null)

This won't compile in AS3 projects using the library and the used code is beyond my reach. Is there a way to do this, perhaps macros?

1 Answers

Well, that's a great question. And, it turns out there is a way to do it!

Basically, __arguments__ is a special identifier on the Flash target, mostly used to access the special local variable arguments. But it can also be used in the method signature, in which case it changes the output from test(args: *) to test(...__arguments__).

A quick example (live on Try Haxe):

class Test {
    static function test(__arguments__:Array<Int>)
    {
        return 'arguments were: ${__arguments__.join(", ")}';
    }
    static function main():Void
    {
        // the haxe typed way
        trace(test([1]));
        trace(test([1,2]));
        trace(test([1,2,3]));

        // using varargs within haxe code as well
        // actually, just `var testm:Dynamic = test` would have worked, but let's not add more hacks here
        var testm = Reflect.makeVarArgs(cast test);  // cast needed because Array<Int> != Array<Dynamic>
        trace(testm([1]));
        trace(testm([1,2]));
        trace(testm([1,2,3]));
    }
}

Most importantly, this generates the following:

static protected function test(...__arguments__) : String {
    return "arguments were: " + __arguments__.join(", ");
}
Related