digitalmars.D.learn - Indirect access to variables.
Compile-time: Is there a 'foo1' that yields 1 from the snippet below? ``` void main() { import std.stdio; size_t var1 = 1; char[4] Txt = cast(char[4])("var1"); writeln(foo1(Txt)); } ``` Similarly, execution-time, is there a foo2 that wields 2 from the snippet below: ``` void main() { import std.stdio; size_t var2 = 2; char[4] Txt; // Txt = various things at run-time; // But finally: Txt = cast(char[4])("var2"); writeln(foo2(Txt)); } ```
Dec 29 2023
On Friday, 29 December 2023 at 17:11:49 UTC, DLearner wrote:Compile-time: [...] Is there a 'foo1' that yields 1 from the snippet below? [...] Similarly, execution-time, is there a foo2 that wields 2 from the snippet below: [...]**compile-tome** ```d void main() { import std.stdio; size_t var1 = 1; size_t var2 = 8; writeln(mixin(var1.stringof)); writeln(mixin(var2.stringof)); } ``` **run-tome** Given the information you provide I'd say you can use an associative array: ```d size_t*[string] registry; void main() { import std.stdio; size_t var1 = 1; size_t var2 = 8; registry[var1.stringof] = &var1; registry[var2.stringof] = &var2; writeln(*registry[var1.stringof]); writeln(*registry[var2.stringof]); } ``` but take care to the entries lifetime, that's basically not safe as this escapes stack addresses.
Dec 29 2023
On Friday, 29 December 2023 at 21:25:44 UTC, user1234 wrote:[...]Thanks, and the ideas are useful, but please see below, suppose: ``` void main() { size_t var1 = 1; size_t var2 = 3; size_t var3 = 5; // ... Many other variables defined. char[4] VarName; // ... // And some complicated logic finishes: VarName = cast(char[4])("var2"); // _Without_ previously storing the addresses of // all the 'var' variables, how do I get access // to the variable currently (run-time) named in VarName? // // Is there a compiler-provided // 'introspection' function that would do this? // // Labouring the point: If there is an int variable intVar, // whose name ("intVar") is held in a string variable strVar, // then there is a compiler function __fnAddrVar() such that // assert(__fnAddrVar(strVar) == &intVar) // is true? } ```
Dec 30 2023