#if macro
import haxe.macro.Context;
import haxe.macro.Expr;
#end
class Main {
static function main() {
var a = "hi";
trace(a);
trace(nameOf(a));
}
static macro function nameOf(e:Expr):Expr {
Context.typeExpr(e);
return switch (e.expr) {
case EConst(CIdent(s)):
macro $v{s};
default:
Context.error("nameOf requires an indentifier as argument", Context.currentPos());
}
}
}
The macro function takes an expression as argument, types it to make sure it exists, and then if it’s an identifier it returns its name, otherwise it errors.
Thank you very much for this verbose code snippet. It works fine! I thought it might be weird to access a variable name that is propably “compiled away” to bytes and wasn’t sure if it was possible at all.