4

In p5.js, to call the setup function you simply write:

function setup() {

}

How did they make it so you call function and then the name, instead of just saying the following?

setup();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Crazy Frog
  • 43
  • 2
  • 2
    The first code snippet is not a function call, but a function declaration. [`setup()`](https://p5js.org/reference/#/p5/setup) is called by the p5.js framework, but you don't "see" this call in your code. – Rabbid76 Feb 20 '21 at 07:31

1 Answers1

5

To use p5.js we don't call the setup function. We define a setup function that code inside of p5.js calls.

In the case where we have code that looks like this:

<script src="../p5/lib/p5.js"></script>
<script>
  function setup() {
    background(100, 0, 100);
  }
</script>

Our setup function is added to the global window object and can be called by code inside of p5.js. If we were running in instance mode, our setup function would not be added directly to the window object, but p5.js would still be able to find it and call it.

For simplicity, let's focus on the case as above where we have written setup and it is attached to the window object.

Looking at the p5.js source code, we see a function called _setup and in that function this code:

if (typeof context.setup === 'function') {
  context.setup();
}

This is where our setup gets called. If we add this alert:

if (typeof context.setup === 'function') {
  if (context === window)alert("context is window");
    context.setup();
}

we can verify that the context object is indeed the window object and _setup is calling the setup function that we created in our code.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Charlie Wallace
  • 1,810
  • 1
  • 15
  • 17