How to call a top level function in a script when there are multiple versions

Tim Fox timvolpe at
Fri Dec 6 00:17:02 PST 2013

I should add - I can work around this pretty easily by simply executing 
a JavaScript fragment in the scope I want, e.g.

engine.eval("if (typeof vertxStop === 'function') vertxStop();", 

So it's not a huge deal, but would be nice to be able to call a top 
level function directly from Java in a specific scope.

On 05/12/13 23:01, Tim Fox wrote:
> I have a ScriptEngine instance which I use many times to execute 
> scripts in different scopes:
> I.e. repeat the following several times with different scripts
> ScriptContext ctx = new SimpleScriptContext();
> Bindings bindings = engine.createBindings();
> ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
> engine.eval(someScript, ctx);
> Some time later I want to invoke a top level function 'vertxStop' in 
> one of those scripts.
> Each script has their own version of function vertxStop as they all 
> have their own scope.
> According to the docs I can invoke a top level function by casting the 
> engine to Invocable:
> Invocable inv = (Invocable)engine;
> inv.invokeFunction("vertxStop");
> But this doesn't let me choose which of the many vertxStop functions I 
> want to execute.
> I looked for a version of invokeFunction which takes a ScriptContext 
> too, but couldn't find one.
> Does anyone know how I can invoke a top level function from a specific 
> scope using the javax.script API?
> Cheers

More information about the nashorn-dev mailing list