Re: A custom name for variables

2020-05-29 Thread solidstate1991 via Digitalmars-d-learn

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", );
// 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.


Re: A custom name for variables

2020-05-29 Thread Liu via Digitalmars-d-learn

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", );
// 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


Re: A custom name for variables

2020-05-28 Thread Steven Schveighoffer via Digitalmars-d-learn

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", );
     // 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


Re: A custom name for variables

2020-05-28 Thread Johannes Loher via Digitalmars-d-learn

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", );
// 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.