Haxe - SWC 中可变数量的参数
Haxe - variable number of arguments in SWC
我正在将一个库从 AS3 移植到 Haxe,我需要制作一个接受可变数量参数的方法。目标是 *.swc 库。
我的问题与 this one 有关,但 none 的建议解决方案输出具有所需签名的方法:someMethod(...params)
相反,生成的方法是:someMethod(params:*=null)
这不会在使用该库的 AS3 项目中编译,而且所使用的代码超出了我的范围。有没有办法做到这一点,也许是宏?
好吧,这是一个很好的问题。而且,事实证明有一种方法可以做到!
基本上,__arguments__
is a special identifier on the Flash target, mostly used to access the special local variable arguments
。但它也可以用在方法签名中,在这种情况下它将输出从 test(args: *)
更改为 test(...__arguments__)
.
一个简单的例子 (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]));
}
}
最重要的是,这会生成以下内容:
static protected function test(...__arguments__) : String {
return "arguments were: " + __arguments__.join(", ");
}
我正在将一个库从 AS3 移植到 Haxe,我需要制作一个接受可变数量参数的方法。目标是 *.swc 库。
我的问题与 this one 有关,但 none 的建议解决方案输出具有所需签名的方法:someMethod(...params)
相反,生成的方法是:someMethod(params:*=null)
这不会在使用该库的 AS3 项目中编译,而且所使用的代码超出了我的范围。有没有办法做到这一点,也许是宏?
好吧,这是一个很好的问题。而且,事实证明有一种方法可以做到!
基本上,__arguments__
is a special identifier on the Flash target, mostly used to access the special local variable arguments
。但它也可以用在方法签名中,在这种情况下它将输出从 test(args: *)
更改为 test(...__arguments__)
.
一个简单的例子 (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]));
}
}
最重要的是,这会生成以下内容:
static protected function test(...__arguments__) : String {
return "arguments were: " + __arguments__.join(", ");
}