www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - A custom name for variables

reply Quantium <qchessv2 gmail.com> writes:
I need to create a variable with custom name, like this
import std;
void main()
{
     string name;
     readf(" %s", &name);
     // some code that generates a variable of type integer and 
value 0
}
Could you help me with that?
May 28 2020
next sibling parent Johannes Loher <johannes.loher fg4f.de> writes:
On Thursday, 28 May 2020 at 20:26:55 UTC, Quantium wrote:
 I need to create a variable with custom name, like this
 import std;
 void main()
 {
     string name;
     readf(" %s", &name);
     // some code that generates a variable of type integer and 
 value 0
 }
 Could you help me with that?
Do you want to create a variable with the name read with readf? If yes, that is not possible. Variable names need to be known at compile time.
May 28 2020
prev sibling next sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 5/28/20 4:26 PM, Quantium wrote:
 I need to create a variable with custom name, like this
 import std;
 void main()
 {
      string name;
      readf(" %s", &name);
      // some code that generates a variable of type integer and value 0
int value = 0;
 }
 Could you help me with that?
If you are asking to have code that uses a runtime string as a variable name, you will not be able to do that in D. You have to know the name at compile time. However, you can store data mapped to string names using an associative array: int[string] variables; variables[name] = 0; // use like writeln(variables[name]) variables[name] = 5; -Steve
May 28 2020
prev sibling next sibling parent Liu <liiudk gmail.com> writes:
On Thursday, 28 May 2020 at 20:26:55 UTC, Quantium wrote:
 I need to create a variable with custom name, like this
 import std;
 void main()
 {
     string name;
     readf(" %s", &name);
     // some code that generates a variable of type integer and 
 value 0
 }
 Could you help me with that?
This is not possible You would need a scripting language in order to do that. What are you trying to do? if your explain better, we may try came up with a better solution
May 29 2020
prev sibling parent solidstate1991 <laszloszeremi outlook.com> writes:
On Thursday, 28 May 2020 at 20:26:55 UTC, Quantium wrote:
 I need to create a variable with custom name, like this
 import std;
 void main()
 {
     string name;
     readf(" %s", &name);
     // some code that generates a variable of type integer and 
 value 0
 }
 Could you help me with that?
This might be possible in certain scripting languages, but not in D. Static fields are generated during compile time, and while something like that is possible using template mixins in the code (famous use in D is Phobos's bitfields, which generates properties for a struct or a class), it's impossible during runtime, and - in extension - by reading a value from console.
May 29 2020