Find variable at run time
    bearophile 
    bearophileHUGS at lycos.com
       
    Fri May 17 15:15:07 PDT 2013
    
    
  
Josh:
> Is something like this possible in D?
>
> void main()
> {
>     int x, y, z;
>     write("Increment which variable: ");
>     string input = readln()[0..$ - 1];
>     findVar(input)++;
>     writeln(x, y, z);
> }
The Go language and its standard library make the usage of such 
runtime reflection much simpler than in D. So I think D has to 
improve on such things.
A starting point:
import std.stdio, std.string;
void main() {
     int x, y, z;
     auto findVar = ["x": &x, "y": &y, "z": &z];
     "Increment which variable: ".write;
     const input = readln.chomp;
     (*findVar[input])++;
     writeln(x, y, z);
}
With __FUNCTION__ you can tell the name of the current function, 
but how do you find the caller function? And how do you find the 
names of the local variables in the caller function?
D is a statically compiled language, and its templates allow to 
do lot of stuff at compile-time. But some run-time reflection is 
handy in many cases.
Bye,
bearophile
    
    
More information about the Digitalmars-d-learn
mailing list