2017-07-18 79 views
3

我產生內部haXe的宏觀int數組,並希望在其應用的功能是這樣的:價值觀的陣列應用在函數內部HAXE宏觀

typedef ComponentIdArray = Array<Int>; 

    // 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(); 
    } 

// Usage 
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] 

既然一切被稱爲編譯時我會喜歡在宏中這樣做。

+1

你想在宏觀背景下或在運行時環境應用的功能? –

+0

宏觀上下文是否意味着編譯時間?好的!基本上,我想在宏觀上做到這一點的原因是以上所有內容都是已知的通信時間。 –

+1

雖然答案可能已經解決,但本文可能也有幫助http://code.haxe.org/category/macros/build-arrays.html –

回答

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); 
} 

正如你所看到的,你還需要定義一個定製predicatedistinct(),因爲你是比較表達式 - 默認情況下它使用簡單的相等檢查(==),這不夠好。

生成的代碼看起來像這樣(如果id_變量聲明inline):

var r = MyMacros.allOfIndices([1, 2]); 
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