Skip to content

Instantly share code, notes, and snippets.

@paulera
Created April 3, 2017 11:55
Show Gist options
  • Save paulera/ce0a2bc2300ca68a7d14eebcfe99ace0 to your computer and use it in GitHub Desktop.
Save paulera/ce0a2bc2300ca68a7d14eebcfe99ace0 to your computer and use it in GitHub Desktop.
Processing example of how to dynamically run javascript code from a String, passing objects to be read and manipulated in the script scope. Originated in this Processing Forum thread: https://forum.processing.org/two/discussion/comment/93357
import javax.script.*;
void setup() {
// creates and object to be manipulated by
// the script
MyClass obj = new MyClass();
// object state BEFORE running the script
println("Before:");
println("message = " + obj.message);
println("count = " + obj.count);
// creates a javascript engine
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("javascript");
// injects the object in the script scope
engine.put("obj", obj);
// runs the script
try {
engine.eval(
"obj.message=\"Hello World!\";" +
"while (obj.count < 5) {" +
" obj.incCount();" +
"}"
);
} catch (Exception ex) {
println (ex.getMessage());
}
// object state AFTER running the script
println("After:");
println("message = " + obj.message);
println("count = " + obj.count);
}
public class MyClass {
public String message;
public int count = 0;
public void incCount() {
this.count++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment