Function restricted variables


#1

I want some variables to only exist in a certain function as I need very similar variables across multiple functions. However, I don’t want them to be reset every single time. The only other solution I can think of is to use ‘atime’, ‘btime’, ‘ctime’ etc. but this is very messy and I’m trying to clean up my code.
So is there any way to create variables that are only recognised by one function but its values aren’t reset every time the function is called upon?


#2

I think the most elegant way would be to have global variables like atime and btime.

Can I ask you to post your functions?


#3

Hi Blosh,

It would be better to post at least an MCVE so people can better understand what you want to do.

Now I think you are referring to a static variable in C++ (for example) and that can be super handy. Sadly you can’t use that in Java.

Now there is (at least) 2 ways of doing it.

The first one is kinda like your solution but using an array instead to clean up the code a bit. So instead of having 3 variable atime, btime and ctime you would only have times[3] as a variable.

Another way is to use classes. It might be overkilling but at least you have it sorted out.

myFunction1 f1;

void setup() {
  frameRate(10);
  f1 = new myFunction1();
}


void draw () {
  f1.run();
  println(f1.getTime());
}


class myFunction1 {
  private int time;
  
  myFunction1() {
    time = 0;
  }
  
  void run() {
    // Your code
    time++;
  }
  
  int getTime() {
    return time;
  }
}

#4

Alright thanks for the feedback, will be sure to use a MCVE for future posts. Yeah I thought about using a class but I think using global variables will just turn out much easier. Thanks :slight_smile: