我有一个问题,将参数传递给宏功能。
我想传递了一个字符串,看起来像这样的功能:
macro public static function getTags(?type : String)
但是有一个编译错误:
haxe.macro.Expr应该是空<字符串>
因此,根据该文件,我把它改成这样:
macro public static function getTags(?type : haxe.macro.Expr.ExprOf<String>)
这一工程,但我怎么能访问字符串值?如果我跟踪我型我得到这样的:
{EXPR => .econst段(CIdent(类型)),POS => #pos(LIB / WX /核心/容器/ ServiceContainer.hx:87:36-40字符)}
我认为,我必须在type.expr
切换,但我的常量包含变量名,而不是价值。我怎样才能访问的价值?而且是有更简单的方式来获得这个值(不带开关为例)。
我认为这是因为调用该函数是不是在一个宏,我觉得我想要做的事情是不可能的,但我更喜欢问。 :)
正如你所提到的,使用variable capture in pattern matching:
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
}
}
注意,如上图所示,宏功能可以仅在输入表达式是一个文本字符串中提取的字符串值。请记住,宏功能在编译时运行,因此它不知道变量的运行时的值。