Subj : Re: evaluateString returns "Undefined" To : Anil Atur From : Igor Bukanov Date : Thu Jul 29 2004 12:04 pm Anil Atur wrote: .... > Context cx = Context.enter(); > String test = "Test"; > 6. > 7. ScriptableObject scope = cx.initStandardObjects(null, true); > 8. > 9. String script2 = "function f(x) { return x; }; " > +"java.lang.System.out.println(f('"+test+"'));"; > 10. > 11. Scriptable threadScope = cx.newObject(scope); > 12. > 13. Object result = cx.evaluateString(threadScope, script2, > "Test", 1, null); > 14. > 15. String report = cx.toString(result); > 16. > 17. System.out.println("report : " + report); > 18. > 19. } > 20. > 21. } > 22. > 23. > > Line Number 15 outputs a string as UNDEFINED .. > > The evaluateString evaluates the function f() and > displays the output as 'Test' from the *script2* . The return object is > the result and when converted to a string *cx.toString(result)* > displays as "*Undefined*" .. How do we go about this ..?? In your program you evaluates the script: function f(x) { return x; };java.lang.System.out.println(f('Test')); Its result should be the result of the last statement which is java.lang.System.out.println(f('Test')); Since System.println in Java returns void, Rhino translates that into undefined object. When you later call cx.toString(result) that will convert that to string and give "undefined" according t the rules of JavaScript. BTW, you omitted Context.exit() call from your program, you MUST always use the pattern: Context cx = Context.enter(); try { Code that use cx } finally { Context.exit(); } Otherwise at best you get memory leak and at worst you end up with potential RuntimeException. Another problem is the line: Scriptable threadScope = cx.newObject(scope); If you want to follow http://www.mozilla.org/rhino/scopes.html , then you should do after the call: threadScope.setPrototype(scope); threadScope.setParentScope(null); Otherwise you are effectively execute your scripts as in: with(threadScope) { your script } In this way all variables declared in the script will be stored not in threadScope, but rather in the original global scope returned by cx.initStandardObjects() and your threadScope would be pretty much ignored. Regards, Igor .