COMMUNITY

Return a variable name itself

I know it is possible to get the class name of an instance and even to tell its Type (platform dependent).

var o = new MyClass();
trace( "Instance is of class " + Type.getClassName( Type.getClass( o ) ) + " and is Type of " + Type.typeof( o ) );

Which prints:
Instance is of class MyClass and is Type of TClass($MyClass)

But how can I return a variable’s name?

Like:

var mySuperCoolVariableName : Int;
Sys.println( Variable.getName( mySuperCoolVariableName ) );

To print:
mySuperCoolVariableName


Thank you :slight_smile:

You can do it with a macro:

#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.

1 Like

Thank you very much for this verbose code snippet. It works fine! :smiley: 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. :+1:

Isn’t it just Sys.println( 'mySuperCoolVariableName' ); because you are already typing the variable name on your keyboard?

1 Like