Find variable at run time

Adam D. Ruppe destructionator at gmail.com
Fri May 17 14:21:34 PDT 2013


Not with local variables, but you can with a struct.

===

import std.stdio;

void main() {
	struct Vars {
		int x;
		int y;
		int z;

		ref int get(string name) {
                       // allMembers gets the names of each member 
as a string
			foreach(member; __traits(allMembers, typeof(this))) {
                                // we're only interested in ints 
because string++ doesn't make sense anyway
				static if(is(typeof(__traits(getMember, this, member)) == 
int)) {
					if(member == name)
						return __traits(getMember, this, member);
				}
			}
			throw new Exception("I don't know " ~ name);
		}

	}

	Vars vars;

	writeln("which variable?");
	vars.get(readln[0 .. $-1])++;
	writeln(vars.x, vars.y, vars.z);
}

===


More information about the Digitalmars-d-learn mailing list