toolness / p5.js-widget

A reusable widget for embedding editable p5 sketches in web pages.
https://toolness.github.io/p5.js-widget/
GNU Lesser General Public License v2.1
162 stars 44 forks source link

Implicit setup() is applied when setup/draw are defined through variable assignment #36

Closed toolness closed 8 years ago

toolness commented 8 years ago

As mentioned in #35:

This implementation only includes functionality to detect standard idiomatic function declarations (FunctionDeclaration in the parser API) of setup/draw. This means that the following sketch will be unmodified and work as intended:

function setup() { createCanvas(200, 200); }

However, the following will be wrapped in an implicit setup() function, and the user's setup() function will actually never be called:

var setup = function() { createCanvas(200, 200); };

This gets even more complicated with ES2015 since there are so many ways to define functions and assign them to variables.

Also, the user can do even weirder things to define setup/draw like assigning directly to window.setup or window["setup"], but we can probably safely assume they won't do that.

An alternative to detecting for all of these edge cases may be to add some code at the end of the implicit setup() that looks something like this:

// Just in case the user actually *did* define setup in a weird way
//  that we didn't detect, call it ourselves.
if (typeof(setup) === 'function') setup();

// Not actually sure if this will work, but you get the idea...
if (typeof(draw) === 'function') window.draw = draw;
toolness commented 8 years ago

Note that the fix I just made doesn't actually work if the user assigns setup/draw to non-function values, but that should be quite rare, I'm guessing.