For everybody that had to deal with Rhino, or was scared off when walking through the tutorials… how to mix Contexts in interpreted mode and how all those Scriptables interact with eachother, and all those other quirks.
I got sick of all the boilerplate code I had to write, so I simplified it so the extend of being maybe even a bit too easy :persecutioncomplex:
As always, sourcecode and JAR available:
http://www.katav.nl/html_stuff2/ => jawnae.js.*
Example 1: (creating a script)
String code = "var my = 'javascript code';"; JsScript script = new JsScript(code); script.execute();
Example 2: (creating a function)
String code = "function sum(a, b) { return a + b; }"; JsFunction func = new JsFunction(code); func.invoke(13, 14);
Example 3: (using a function from an external script)
`
JsScope shared = new JsScope();
String sumCode = “function sum(a, b) { return a + b; }”;
JsFunction func = new JsFunction(code, shared);
String useCode = “var x=3; var y=4; var z=sum(x, y)”;
JsScript script = new JsScript(useCode, shared);
script.execute();
script.eval(“x = y + z;”);`
Example 4: (green threads!!)
`
JsScope scope = new JsScope();
scope.setInterpretedContext(true);
scope.put(“out”, System.out);
String code = “”;
code += “out.println(“step 1”);”;
code += “Thread.yield();”; // continuation!
code += “out.println(“step 2”);”;
code += “Thread.sleep(1000);”; // continuation!
code += “out.println(“step 3”);”;
// thread1: code += “Thread.wait(‘this_is_a_lock’);”;
// thread2: code += “Thread.notify(‘this_is_a_lock’);”;
JsScript script1 = new JsScript(code);
JsScript script2 = new JsScript(code);
JsCPU cpu = new JsCPU();
cpu.addThread(new JsThread(script1));
cpu.addThread(new JsThread(script2));
while(cpu.hasThreads())
{
cpu.tick();
}
`
There is also a debug mode (JsStepper), so that you can read the (local) scope of a function while it is executing.
For more examples: http://www.katav.nl/html_stuff2/source/test/jawnae/js/JsUnitTest.html
Have fun!