我在Haxe宏中生成了一个Int
数组,并想在其上应用一个函数:
typedef ComponentIdArray = Array<Int>;
class MyMacros {
// Each descendant of 'Component' has static member 'id_'
// Convert array of classes to corresponding indices
public static macro function classesToIndices(indexClasses:Array<ExprOf<Class<Component>>>) {
var ixs = [for (indexClass in indexClasses) {macro $indexClass.id_ ;}];
return macro $a{ixs};
}
public static macro function allOf(indexClasses:Array<ExprOf<Class<Component>>>) {
var indices = macro Matcher.classesToIndices($a{indexClasses});
// FIXME
// FIXME 'distinct' is a function from thx.core -- DOES NOT WORK
//var indices2 = macro ($a{indices}.distinct());
return macro MyMacros.allOfIndices($indices);
}
public static function allOfIndices(indices:ComponentIdArray) {
trace(indices);
//... normal function
// currently I call indices.distinct() here
return indices.distinct();
}
}
用法:
class C1 extends Component {} // C1.id_ will be set to 1
class C2 extends Component {} // C2.id_ will be set to 2
var r = MyMacros.allOf(C1, C2, C1); // should return [1,2]
由于编译时已知所有内容,我想在宏中执行此操作。
答案 0 :(得分:2)
KevinResoL的答案基本上是正确的,除非您希望在编译时执行distinct()
(正如您在try.haxe的输出选项卡中看到的那样,生成的JS代码包含thx.Arrays.distinct()
来电。
最简单的解决方案可能是立即在distinct()
:
allOf()
using haxe.macro.ExprTools;
public static macro function allOf(indexClasses:Array<ExprOf<Class<Component>>>) {
indexClasses = indexClasses.distinct(function(e1, e2) {
return e1.toString() == e2.toString();
});
var indices = macro Matcher.classesToIndices($a{indexClasses});
return macro MyMacros.allOfIndices($indices);
}
正如您所看到的,您还需要为predicate
定义自定义distinct()
,因为您正在比较表达式 - 默认情况下,它使用简单的相等性检查(==
),这不够好。
生成的代码如下所示(如果id_
变量被声明为inline
):
var r = MyMacros.allOfIndices([1, 2]);
答案 1 :(得分:1)
.distinct()
仅在调用该函数的模块中有using thx.Arrays
时可用。
使用宏生成表达式时,无法保证调用点具有using
。所以你应该使用静态调用:
这适用于您的代码:
public static macro function allOf(indexClasses:Array<ExprOf<Class<Component>>>) {
var indices = macro Matcher.classesToIndices($a{indexClasses});
var e = macro $a{indices}; // putting $a{} directly in function call will be reified as argument list, so we store the expression first
return macro thx.Arrays.distinct($e);
}
另请参阅此haxe上的工作示例:http://try-haxe.mrcdk.com/#9B5d6