[英]Passing parameters to a Haxe macro
我在將參數傳遞給宏函數時遇到了問題。
我想將一個字符串傳遞給一個如下所示的函數:
macro public static function getTags(?type : String)
但是有一個編譯錯誤:
haxe.macro.Expr 應該是 Null<String>
因此,根據文檔,我將其更改為:
macro public static function getTags(?type : haxe.macro.Expr.ExprOf<String>)
這有效,但我如何訪問字符串值? 如果我跟蹤我的類型,我會得到這個:
{ expr => EConst(CIdent(type)), pos => #pos(lib/wx/core/container/ServiceContainer.hx:87: characters 36-40) }
我認為我必須打開type.expr
,但我的 const 包含變量名,而不是值..如何訪問該值? 有沒有更簡單的方法來獲得這個值(例如,沒有開關)。
我認為這是因為對函數的調用不在宏中,我認為我想做的事情是不可能的,但我更喜歡問。 :)
class Test {
macro public static function getTags(?type : haxe.macro.Expr.ExprOf<String>) {
var str = switch(type.expr) {
case EConst(CString(str)):
str;
default:
throw "type should be string const";
}
trace(str);
return type;
}
static function main() {
getTags("abc"); //Test.hx:10: abc
var v = "abc";
getTags(v); //Test.hx:7: characters 13-18 : type should be string const
}
}
請注意,如上所示,如果輸入表達式是文字字符串,宏函數只能提取字符串值。 請記住,宏函數在編譯時運行,因此它不知道變量的運行時值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.