I am curious about how to run p5.js code within a running sketch, so the code changes as the program runs? The code should come from a user input (like a text field) or from a function (like an api-call to GPT-3 or similar). I looked at eval() and new Function() but can’t get them to work interactively + both seem somewhat dangerous to use…
Hi Andreas! Nice to see you here I’m not sure but maybe it would help to check how p5.widget does it? Thanks to @davepagurek for reminding me of the name of that tool.
Hi Raphaël!
Oh cool, that is a nice tool. However, what I am looking for is slightly different (and sorry if it was not clear from my original question). Essentially want to take a string of text containing p5js code (for instance outputted by GPT-3) and run that code from within the script itself.
As an example, I would ask GPT-3 to make me a beautiful pattern of circles in p5.js, and instead of manually copy-pasting the output into my code editor, I want to directly run the code outputted by GPT-3. If that makes sense?
const scriptTag = document.createElement('script')
scriptTag.setAttribute('type', 'text/p5')
scriptTag.innerHTML = yourSourceCodeHere
document.body.appendChild(scriptTag)
// Turn the tag into an editor widget:
window.p5Widget.replaceScript(scriptTag)
Also it’s probably worth mentioning that it’s still somewhat dangerous to run arbitrary code without looking at it. The widget works by creating an <iframe> tag with a page that runs your code, so it’s at least isolated from the rest of your page and is probably more secure than eval()ing the code directly, but proceed with caution still
Sorry for the late reply. I don’t want to use the widget if possible. Essentially want to take a string of text containing p5js code (for instance outputted by GPT-3) and run that code from within the script itself. Any ideas?
Actually, you can collect and execute code interactively, but as you and @davepagurek have noted, that could be dangerous.
The following uses prompt() to accumulate code that can be typed or pasted in:
let codeToExecute = "";
function setup() {
createCanvas(200, 200);
}
function draw() {
// accumulate code to execute during each call to draw()
let newCode = prompt("Additional code to accumulate (Cancel to stop draw() cycling): ");
if (newCode === "" || newCode == null) {
noLoop();
} else {
codeToExecute += newCode;
eval(codeToExecute);
}
}
This code was pasted in at the prompt to produce the image that follows below it:
Whether this is dangerous depends upon how much the source of the code can be trusted. When a user is free to enter code to be executed, it’s time to get nervous.