[英]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.