Get variable symbol name that was passed to a paramater?

Timon Gehr timon.gehr at gmx.ch
Sat Nov 9 16:51:35 PST 2013


On 11/09/2013 10:12 AM, Rob T wrote:
>
> I am wondering if there's a way to pass only the variable and have the
> inspect function determine the variable's symbol name as passed rather
> than have to pass both the name and value separately?
> ...

Well, yes, but the following does not scale that well, and it is 
somewhat fragile, since there is no way to get column information.

import std.stdio;
import std.string;
import std.algorithm;
import std.range;
import std.conv;

template LineCache(string f){ enum LineCache = 
import(__FILE__).splitLines(); }

void inspect(string f=__FILE__,int l=__LINE__,T)( T value ){
     enum 
name=LineCache!__FILE__[l-1].find("inspect").drop("inspect".length).find("(").drop(1).until!(a=>a==')').to!string.strip;
     writeln(name ~ " = ", value);
}

void main(){
     int a;
     int b=3;
     inspect(a);
     inspect(a+2);
     inspect(a+b);
}


$ dmd -J. -run tt.d
a = 0
a+2 = 2
a+b = 3



More information about the Digitalmars-d-learn mailing list