secret
Created

MultiScopes.java

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
package jsr223;
 
import javax.script.*;
import java.io.InputStreamReader;
 
public class MultiScopes {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("Clojure");
 
engine.put("x", "Mark");
// print global variable "x"
engine.eval("(println x)");
engine.eval("(defn say-hello [bar] (println (str \"Hello \" bar)))");
engine.eval("(say-hello x)");
 
engine.eval(new InputStreamReader(MultiScopes.class.getResourceAsStream("/testing.clj")));
 
engine.eval("(testing/say-hello-from-testing x)");
 
Object value = engine.eval("(+ 5 6)");
 
System.out.println("Value is " + value);
System.out.println("Value's class is " + value.getClass().getName());
 
// Now, pass a different script context
ScriptContext newContext = new SimpleScriptContext();
Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
 
// add new variable "x" to the new engineScope
engineScope.put("x", "world");
 
// execute the same script - but this time pass a different script context
engine.eval("(println *clojure-version*)", newContext);
engine.eval("(println *ns*)", newContext);
engine.eval("(println user/x)", newContext);
engine.eval("(say-hello x)", newContext);
// the above line prints "world"
 
manager.getEngineByName("Clojure").eval("(say-hello x)", newContext);
}
}
gistfile2.txt
1 2 3 4 5 6 7 8 9 10
Mark
Hello Mark
Hello there Mark, how are you?
Value is 11
Value's class is java.lang.Long
{:major 1, :minor 3, :incremental 0, :qualifier alpha4}
#<Namespace user>
world
Hello world
Hello world

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.