linking variables by name

Hi all, need to know if is there any possibility to get variable value by some kind of "linking" it by its name.

For example, having this code

#include <LiquidCrystal.h>

  LiquidCrystal lcd(8,9,4,5,6,7);
  int myvar = 10;
  
  String mystr= "myvar";

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print(mystr);

}

void loop() {
}

... on LCD I can see string "myvar". Now I would like to get and display value of variable listed in string mystr, it means "10". Is it possible to do?

Thanks for any advice
LumpTom

Is it possible to do?

Not that way. At compile time, names are converted to addresses. Throughout the rest of the code, the addresses are substituted when a name appears.

If you explain what you are really trying to do, perhaps we could offer suggestions.

Why don't you just lcd.print(myvar); ?

JimboZA:
Why don't you just lcd.print(myvar); ?

because my intention is to do some kind of parametrized display output of different variables by one void routine with name of variable and other parametters (position on LCD adn length for example) as input and then value of this variable should be displayed ...

There's the # stringify operator

lumptom:
because my intention is to do some kind of parametrized display output of different variables by one void routine with name of variable and other parametters (position on LCD adn length for example) as input and then value of this variable should be displayed ...

If the identify of the variable being output is to be hard-coded, that's very easy to do:

    int myValue=4;
    displayValue("myValue=", myValue, x, y);

    ...

void displayValue(char *legend, int value, int x, int y)
{
    ...

Your original description sounded almost as if you were going to receive a variable name in textual form and then do something with the value of the corresponding variable. For example if you had a serial interface that received textual commands, you might have a requirements like that. But I don't think that's the case here.

this si not exactly what I mean, idea is to have indexed arrays with parameters like position, length, variable name and then void display routine, similar to that

char var1;
int var2;
float var3;

String vars[] = { "var1", "var2", ... "varx" };
int xpos[] = { 0, 5, 7 ... 15};
int ypos[] = { 0, 0, 0, ... 1};
int legths[] = { 2, 5, 3, ... 2};

int index=2;

display_var(vars[index], xpos[index], ypos[index], lengths[index]);

void display_var(String varname, int xxpos, int yypos, int llen); {
...
  lcd.setcursor(xpos,ypos);
  lcd.print(@varname,llen);              // @ is only example how i imagin it
}

let you take it only as example, i know that @ will not work, but i am trying find similar type of solution ...

need to note, that variable itself may be different types .... so maybe it has no simple solution, if i think about it ....
i planed first to convert incoming variable value (any type) to string and then play with it (formating) and display it, but first i have to get somehow value of variable through its name ...of course it must be always global variable which must be aceessible inside the void

AWOL:
There's the # stringify operator

could you please show some code example how to use it? i didn't found it in reference :roll_eyes:

http://gcc.gnu.org/onlinedocs/cpp/Stringification.html

(Google is a good friend of mine - you should get acquainted)

lumptom:
this si not exactly what I mean, idea is to have indexed arrays with parameters like position, length, variable name and then void display routine, similar to that

That's all well and good, but where do these variable names come from? If they're from an external source then you need some sort of dictionary lookup system. It's not especially difficult to implement once you get the concept, but would be a bit challenging for a novice. If the values are going to be hard-coded then passing the values in by name is IMO the wrong approach and you should be looking at the sort of solution I outlined previously.

AWOL:
(Google is a good friend of mine - you should get acquainted)

mine too, if i know what to find ..... however i tried to figure out things from link you posted, but it is upon my programmer experience ... should you be so kind and place some change in my code example to show me how to use it? my appologize, there are things i am not able to imagin how they works ...

i tried to use (if you look at my code example)

lcd.print(#varname)

but get error "stray '#' in program"

PeterH:
That's all well and good, but where do these variable names come from? If they're from an external source then you need some sort of dictionary lookup system. It's not especially difficult to implement once you get the concept, but would be a bit challenging for a novice. If the values are going to be hard-coded then passing the values in by name is IMO the wrong approach and you should be looking at the sort of solution I outlined previously.

they comes from previous code, if i can say it so, but they will not be hard-coded, if i understand well what do you mean it .... let's say that these variables are some kind of settings for next code run, and i want to change their initial values (using buttons), and display them during that process .... some of them will be int number, some of them will be float, some will be strings .... so i wanted to write universal display routine, which i could write all these variable values on LCD without writing extra code to display each simple variable on different position .... this was plan

Is it possible the solution is as simple as having a separate method for displaying the data - something like this - which I've just made up

 void displayStuff(message, xposn, yposn){
    // code to display the message
  }

You can then call this method from different places and pass in different variables - for example

void loop() {

   // lots of program code is omitted

   // at this point in the program
      displayStuff(temperature, 12, 5);

   // more program code omitted

   // and somewhere else in the program
      displayStuff(loudness, 9, 3);

}

...R

lumptom:
Hi all, need to know if is there any possibility to get variable value by some kind of "linking" it by its name.

You can set up an array of names which points to addresses.

so i wanted to write universal display routine, which i could write all these variable values on LCD without writing extra code to display each simple variable on different position

Overloaded functions can help with that a bit.

Close to what Nick says, I say you could set up an array of names and a matching array of pointers compiled to link to the variable by the name. What name you find, that same index pointer will hold the address. Because that is what pointers do, hold addresses and work in arrays. You can keep the names in flash but I'm not sure about the pre-set pointers. You can even have pointers to functions.

If all your variables could fit into an array, you wouldn't need pointers, at 2 bytes each. So maybe you have 30 different ints with different names, if you code them as an array the names will be remembered in the array of names as above. The index of the name is the index of the data. This way would be more compact, let you have more variables to address.

But there's another way. All code is stored in flash so a large switch-case is kind of a flash table.
It could be written to look at the 1st 4 letters of a word as an unsigned long for the switch and every case would have an unsigned long and then strcmp() with as many variable names as start with the same 4 chars. If there's many then look at the next 4 letters by switch-case. Success at strcmp() should set a pointer to the variable.

BTW, strcmp() is a C string array function. The AVR environment is far on the tiny side to be doing much with C++ String objects. Strings are fatter and to add a char they replicate themselves, shotgunning your heap even if you have the free() fix. If you can, learn C string arrays for AVR.

For example, if you wanted to find me which would help you more my name or my address?

Wouldn't I need you name to look up your address?

I think he wants user access to variables.

they comes from previous code, if i can say it so, but they will not be hard-coded, if i understand well what do you mean it

I'm still not entirely convinced from what you've said that you actually need to look up a variable by name, but you might.

There are lots of alternative ways to implement it, depending how clever a coder you are and how important it is to minimise code space, memory use, programming time, maintenance costs and so on.

I suggest there are two parts to the problem. First you have to have a list of names that are available to be selected. Second, you have to be able to do (something) to the named variable. You have said that you want to be able to display the value as a string, but you haven't said whether that's all you want.

The completely general solution would be to define an abstract class that provided the interface to let you do all the things you want to do to these named values, and define a map class which enabled you to store and look up an instance of that abstract class by name, and implement concrete classes for each data type that you needed to support. Then declare and populate the map with instances representing all the variables you want to be accessible. That part can be made more concise by using macros to populate the map, and using the #stringify operator within the macro to derive a string containing the symbolic name of each variable you want included in the map.

The amount of code involved would be small, probably 40 - 50 lines of code for the framework, and a couple of lines per named variable. An experienced coder could probably write and test it in half an hour or so. But hopefully you have got some idea now of the amount of complexity involved in solving this problem properly. I'd expect that to be quite a daunting project for a novice, and I would have thought in almost all cases it was not worth the bother.

A much easier solution would be to hard-code a function that accepted a variable name as an argument and just did a sequence of else if(strcmp ... calls to work out what the variable name is and do whatever-it-is to that variable. If the goal was to convert a value to a display string then inside the code block for each variable you could use a sprintf() call with the appropriate format string to print the value to the specified output buffer. If you wanted to do something else to these variables, you'd need to do a copy-and-paste to produce a whole new function that had similar logic to match the variable name, and did whatever other operation you wanted to support. If you wanted to be able to offer a list of variable names to select from, you would add a const array of strings and simply hard-code the names of the supported variables. It's not elegant, not very flexible, and not very maintainable, but avoids having to do anything clever.

OK, one afte another .... first maybe more clarification in my intention what to do. Globaly, i want to have main loop, which will serve "input screen" based on button action ... something like this:

void loop() {
    read button
    based on button 
      do
         move input to next/prev variable (change index) - left/right btn
      or
         change value of variable based on predefine parameters - up/down btn
         write variable on LCD
      or exit if select button pressed
      goto next read
}

So, this give answer to Robin2 approach ...

Robin2:
You can then call this method from different places and pass in different variables - for example

void loop() {

// lots of program code is omitted

// at this point in the program
      displayStuff(temperature, 12, 5);

// more program code omitted

// and somewhere else in the program
      displayStuff(loudness, 9, 3);

}




...R

... i want to have only one display void call, so this is reason why have it full parametrized

Now about Nick's idea ...

.... sounds good, because i planed to use several arrays for defining all parameters with common indexing ..... but i have very minimal C++ knowings, so i don't know how to define pointers or array of pointers it and use it .... i am not sure, that i am able to discover it and write it well in first attempt and i need to ask it anyway, so rather i am asking it just now ..... if you could be so kind and use my sample code 7 replies upwards and write into it some syntax example of defining pointers and use it in voide header and inside void to get variable value, and finaly syntax for void call .... i am asking it because expecting that it has some special syntax in all mentioned parts.

thanks all of you guys for help

Using an array of pointers to variable only works if all of your variables are of the same type.