Run Javascript from a String in Processing

snippet

Originally posted as GitHub Gist on 03 Apr 2017 (details)


Source: https://gist.github.com/paulera/ce0a2bc2300ca68a7d14eebcfe99ace0

Description: 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


processing-run-script-example.pde

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++;
  }
}