我在向宏函数传递参数时遇到问题。
我想将一个字符串传递给一个如下所示的函数:
macro public static function getTags(?type : String)
但是出现编译错误:
haxe.macro.Expr should be 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 包含变量名称,而不是值。我如何访问该值?有没有更简单的方法来获取这个值(例如没有开关)。
我认为这是因为对函数的调用不在宏中,而且我认为我想做的事情是不可能的,但我更喜欢问。 :)
最佳答案
正如您所提到的,使用 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
}
}
请注意,如上所示,如果输入表达式是文字字符串,则宏函数只能提取字符串值。请记住,宏函数是在编译时运行的,因此它不知道变量的运行时值。
关于macros - 将参数传递给 Haxe 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22899980/