【问题标题】:Passing parameters to a Haxe macro将参数传递给 Haxe 宏
【发布时间】:2014-04-06 21:00:08
【问题描述】:

我在将参数传递给宏函数时遇到问题。

我想将一个字符串传递给一个如下所示的函数:

macro public static function getTags(?type : String)

但是有编译错误:

haxe.macro.Expr 应该为 Null

因此,根据文档,我将其更改为:

macro public static function getTags(?type : haxe.macro.Expr.ExprOf<String>)

这行得通,但我怎样才能访问字符串值?如果我追踪我的类型,我会得到:

{ expr => EConst(CIdent(type)), pos => #pos(lib/wx/core/container/ServiceContainer.hx:87: 字符 36-40) }

我认为我必须打开type.expr,但我的 const 包含变量名称,而不是值。我如何访问该值?有没有更简单的方法来获得这个值(例如没有开关)。

我认为这是因为对函数的调用不在宏中,并且我认为我想做的事情是不可能的,但我更喜欢问。 :)

【问题讨论】:

    标签: macros haxe


    【解决方案1】:

    正如你所提到的,使用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
        }
    }
    

    请注意,如上所示,宏函数只能在输入表达式为文字字符串的情况下提取字符串值。请记住,宏函数是在编译时运行的,因此它不知道变量的运行时值。

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      相关资源
      最近更新 更多