简体   繁体   中英

Haxe macro: quote field properly

what is the proper way to (manually) quote a field?

consider the following example:

var name = "$type";
if(name.startsWith("$")) name = "@$__hx__" + name;
var e = macro {$name: "value"};

Instead of name.startsWith("$") , what is the proper way to check if the field name should be quoted?

That's the way to do it...

All other quoting – except for leading $ – should already happen during reification.

class Test {
    static macro function makeObject(key:String, value:haxe.macro.Expr)
    {
        if (StringTools.startsWith(key, "$"))
            key = "@$__hx__" + key;
        return macro @:pos(haxe.macro.Context.currentPos()) { $key : $value };
    }

    static function main()
    {
        trace(makeObject("a", 1));
        trace(makeObject("0", 1));
        trace(makeObject(":", 1));
        trace(makeObject("$a", 1));
    }
}

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