how to convert string to variable

RazRaz
edited March 2016 in How To...

how can I convert String to variable? like: String a="int x=100"; and now I will convert it to variable in the sketch. how to do this?

Tagged:

Answers

  • edited March 2016

    Short answer, you can't. There is no such way to create executable commands from a string.

    You can however develop a system with which to analyse the string and store a given value to its respective variable in a predetermined array.

    Like this:

    String[] variables = {"x", "a", "b", "c", ...};
    int Is, If;
    int[] values = new int[4];   //same length as variables[]
    
    void setup(){
    }
    
    void draw(){
      String a="int x=158;";
    
      if (a.indexOf("int ")!=-1){
        for (int i=0; i<variables.length; i++){
          Is = a.indexOf("int ")+4;
          If = a.indexOf("=");
          if (trim(a.substring(Is, If)).equals(variables[i])){
            Is = a.indexOf("=")+1;
            If = a.indexOf(";");
            values[i] = int(a.substring(Is, If));
          }
        }
      }
    
      println(values[0]);
    }
    

    It is obvious that to use more data types you need to enhance the code.

  • RazRaz
    edited March 2016

    Thank you! I have 2 questions: 1) how can I do if sentence which check where is an character or string (which place)? Like

    String a="int x=0";

    if "n" is in the second place?

    2) How can I convert string to variable name? Like: String b="x";

    int (string b)=0;

    How can I convert it to int x=0;?

  • Both your questions are answered in my example !

    1) https://processing.org/reference/String_indexOf_.html

    2) You cannot just create lines of executable code from input strings... The way to create new variables is as I have shown. With an indication array storing the variable's name and a value array storing its value.

Sign In or Register to comment.