Created
April 3, 2017 11:55
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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