# Calling functions with variables

**URL:** <https://discourse.processing.org/t/calling-functions-with-variables/30001>\
**Category:** Beginners\
**Created:** [May 10, 2021, 1:13am UTC](https://discourse.processing.org/t/calling-functions-with-variables/30001 "2021-05-10T01:13:54Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![Schred](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/schred/32/13146_2.png) [@Schred](https://discourse.processing.org/u/Schred)\
**Post date:** [May 10, 2021, 7:05am UTC](https://discourse.processing.org/t/calling-functions-with-variables/30001/6 "2021-05-10T07:05:10Z")

</div>

This might be a somewhat more efficient and safer approach, although it probably doesn’t matter too much:

```processing
import java.lang.reflect.*;

Method[] scenes;

void setup() {
  scenes = getMethodsStartingWith("scene");
}

void draw() {
}

Method[] getMethodsStartingWith(String prefix) {
  try {
    ArrayList<Method> list = new ArrayList<Method>();
    Method[] all = getClass().getDeclaredMethods();

    for (Method method : all)
      if (method.getName().startsWith(prefix))
        list.add(method);

    return list.toArray(new Method[0]);
  } catch (SecurityException e) {
    e.printStackTrace();
  }

  return new Method[0];
}

void mousePressed() {
  try {
    scenes[int(random(scenes.length))].invoke(this);
  } catch (ReflectiveOperationException e) {
    e.printStackTrace();
  }
}

void scene1() {
  print(1);
}

void scene2() {
  print(2);
}

void scene3() {
  print(3);
}

```

Instead of having to find the method and thereby risk getting an exception and wasting time every mouse press, this code only searches through all the methods once and then stores the ones we need in an array.

The downside to this is of course that it’s not as clean as just doing `method(...)` and since it has to search through all methods in the beginning (which I suspect PApplet has a lot of) while `method(...)` probably just calls `getMethod(name)` behind the scenes, I’m not sure how often `mousePressed` has to be called for this version to be better than the other.

---

_[View the full topic](https://discourse.processing.org/t/calling-functions-with-variables/30001)._
