title: Is there a language-independent way to add a function to JSR223 scripting bindings?
body: <p>The <a href="http://docs.oracle.com/javase/6/docs/api/javax/script/Bindings.html" rel="nofollow">JSR223 <code>Bindings</code> class</a> allows you to expose arbitrary Java objects to scripting languages. But they have to be objects. I would like to define a function <code>quit()</code> that can be called from the scripting environment that turns into <code>quitObject.run()</code> in Java. But JSR223 doesn't define the concept of a function object. Is there a language-independent way to do the following in Javascript, namely to take a Runnable() and create a function in the scripting environment?</p>
  
  <pre><code> static private Object asFunction(ScriptEngine engine, Runnable r) 
      throws ScriptException
   { 
          final Bindings bindings = engine.createBindings();
          bindings.put("r", r);
          return engine.eval(
            "(function (r) { var f = function() { r.run(); }; return f;})(r)",
            bindings);
   }
  
   Runnable quitObject = /* get/create a Runnable here */
   Bindings bindings = engine.createBindings();
   bindings.put("quit", asFunction(engine, quitObject));  
  </code></pre>
  
  <p>With the builtin Javascript support for JSR223 this creates a <code>sun.org.mozilla.javascript.internal.InterpretedFunction</code> which does what I want. But it obviously won't work in Jython or whatever, and I'd like to make this language-independent.</p>
  
  <p>I don't want my script users to have to type <code>quitObject.run()</code> as that's clumsy, and I don't want to parse script input to find <code>quit()</code> as it could be buried within other code.</p>