[英]haxe: different code inside macro reification based on variable value
This works ok: 这样可以正常工作:
//somewhere in Foo:
static function bar(arg:StringMap<Dynamic>) {trace(arg.toString())}
...
//somewhere in build macro:
var myArr = [macro "k1"=>100, macro "k2"=>200, macro "k3"=>300];
var newExpr = macro {
Foo.bar($a{myArr});
}
But in reality sometimes myArr.length == 0 and this gives compilation error: 但是实际上有时myArr.length == 0,这会导致编译错误:
Array<Unknown<0>> should be haxe.ds.StringMap<Dynamic>
So I should replace $a{myArr} with null or new StringMap() if the length of myArr is zero, but how can I do this? 因此,如果myArr的长度为零,我应该将$ a {myArr}替换为null或新的StringMap(),但是我该怎么做呢?
Currently I did this: 目前,我这样做:
var newExpr = myArr.length == 0 ?
macro {
Foo.bar(null);
} : macro {
Foo.bar($a{myArr});
};
But in reality the code in macro is bigger... 但实际上,宏中的代码更大……
您可以使用${}
在宏验证内运行条件
var newExpr = macro Foo.bar(${myArr.length == 0 ? macro null : macro $a{myArr}});
The solution is very easy: 解决方案非常简单:
var myArr = [macro "k1"=>100, macro "k2"=>200, macro "k3"=>300];
...
var arrExpr = myArr.length == 0 ? macro new Map<String, Dynamic>() : macro $a {myArr};
var newExpr = macro {
Foo.bar($arrExpr);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.