1

Is it possible to get the class/struct/other variables value during runtime in dlang to get/set its value? If yes how to do that please provide example. And also is it possible to get the runtime variable value?

Ex:

class S{ int svariable = 5;}
class B { int bvariable = 10;}
void printValue(T, T instanceVariable, string variableName) {
    writeln("Value of ",  variableName, "=", instanceVariable.variableName);
}

Output:

Value of svariable = 5;
Value of bvariable = 10;

Max Alibaev
  • 681
  • 7
  • 17
Hakuna Matata
  • 755
  • 3
  • 13
  • There has been some talk about [std.reflection](http://forum.dlang.org/post/rxrlggihbstxxriswwnp@forum.dlang.org) a bit ago. – greenify Aug 10 '16 at 02:31
  • 1
    Yes, I have gone through that thread but nothing available as library. While googling i just come across witchcraft same answer from @mitch_. – Hakuna Matata Aug 10 '16 at 04:55

2 Answers2

6

There is a library named witchcraft that allows for runtime reflection. There are examples of how to use it on that page.

mitch_
  • 1,048
  • 5
  • 14
4

I'd first recommend trying a reflection library like @mitch_ mentioned. However, if you want to do without an external library, you can use getMember to get and set fields as well as invoke functions:

struct S {
    int i;
    int fun(int val) { return val * 2; }
}

unittest {
    S s;
    __traits(getMember, s, "i") = 5; // set a field
    assert(__traits(getMember, s, "i") == 5); // get a field
    assert(__traits(getMember, s, "fun")(12) == 24); // call a method
}
rcorre
  • 6,477
  • 3
  • 28
  • 33
  • Actually, this is for compile-time reflection and you asked for runtime. So yeah, use witchcraft. – rcorre Aug 12 '16 at 11:21