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

A. Sundararajan sundararajan.athijegannathan at
Fri Dec 6 03:51:12 PST 2013

Invocable uses script engine 'default' ScriptContext. For the default 
ScriptContext, there are getter/setter methods in 

If you flip a different ScriptContext to be your default context, 
Invocable methods will search/invoke functions from that (new default) 
script context.

Hope this helps,


On Friday 06 December 2013 01:47 PM, Tim Fox wrote:
> 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();", 
> theCorrectScriptContext);
> 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