Using p5 Globals in Top-Level Code
One of the unintuitive aspects of p5 that beginners often make is using
p5 globals in their “top level” code, i.e. outside of setup()
and draw()
:
Believe it or not, this sketch doesn’t work, and will result in the following error being thrown:
ReferenceError: color is not defined
The full reasoning and workaround for this is described in the p5 FAQ, suffice to say that programmers of all experience levels encounter it a lot.
It’s hard to detect such errors with 100% accuracy, but in #1130 I added some code that attempts to detect it, and in #1256 I improved on it so that the following console message is now displayed when the above sketch runs:
Did you just try to use p5.js's color() function? If so, you may want to move it into your sketch's setup() function. For more details, see: https://github.com/processing/p5.js/wiki/Frequently-Asked-Questions#why-cant-i-assign-variables-using-p5-functions-and-variables-before-setup
I wish there was an easy way to get feedback on whether users actually find this message helpful. I can think of a few solutions to this, but more on that in a future blog post!