Saving a variable

#1

Hi i want to save a variable inside draw without it changes its value. How do I do that?

#2

as for me, i not understand your question.
so any answer would just be guesswork.

1 Like
#3

Look at saveStrings and loadStrings

  • If the file is there, you can load it and copy in the variable

  • If the file is not there, give the variable an initial value and write it to the file

With this when you run the sketch next time it can load the variable value

#4

When you don’t mean saving a variable during different runs of a sketch but with one run of the sketch see here:


int myVar = 7; 

void setup() {
  size(200, 200);
  background(111); 
  myVar = 8;
}

void draw() {
  background(111); 
  text( myVar, 29, 29);
}

example with changing the var when pressing 0…9 on the keyboard



int myVar = 7; 

void setup() {
  size(200, 200);
  background(111); 
  myVar = 8;
}

void draw() {
  background(111); 
  text( myVar, 29, 29);
}

void keyPressed() {
  if (key>='0'&&key<='9') 
  {
    myVar=key-48;
  }
}

and a version with storage on Hard Drive when the variable value has to be known when running the sketch the next time (tested on Windows)



int myVar = 7; 

void setup() {
  size(200, 200);
  background(111); 

  File f1 = new File(dataPath("")+"//.");
  if (!f1.exists()) {
    // msg
    println("making data path");
  }//if

  f1 = new File(dataPath("")+"//init.txt");
  if (f1.exists()) {
    String[] in=loadStrings(dataPath("")+"//init.txt");
    myVar = int(in[0]);
  } else {
    println("no");
    save();
  }
}

void draw() {
  background(111); 
  text( myVar, 29, 29);
}

void keyPressed() {
  if (key>='0'&&key<='9') 
  {
    myVar=key-48;
  }

  // every time it's changed we save it
  save();
}

void save() {
  String[] listToSave = new String[1]; 

  listToSave[0]=str(myVar); 
  saveStrings(dataPath("")+"//init.txt", listToSave);
}
//

Chrisir