简体   繁体   中英

Passing parameters to a Haxe macro

I've got a problem with passing parameters to a macro function.

I would like to pass a string to a function that looks like this:

macro public static function getTags(?type : String)

But there's a compilation error:

haxe.macro.Expr should be Null<String>

So, according to the documentation, I changed it to this:

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

That works, but how can I access to the string value? If I trace my type I get this:

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

I think that I have to switch on type.expr , but my const contains the variable name, not the value.. How can I access the value? And is there an easier way to get this value (without switch for example).

I think that it's because the call to the function is not in a macro, and I think that the thing I want to do is not possible, but I prefer ask. :)

As you have mentioned, use 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
    }
}

Notice that as shown above, the macro function can only extract the string value if the input expression is a literal string. Remember that macro function is run at compile-time, so it doesn't know a variable's runtime value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM