Search code examples
javatypeerrornashorn

Nashorn fails to execute MATH function


Am using Nashorn script engine in java for evaluating expressions,

the below code for log works,

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("noshorn");
engine.eval("Math.log(99);");

whereas for log10 fails,

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("noshorn");
engine.eval("Math.log10(99);");

it throws an exception saying,

Caused by: <eval>:1 TypeError: Cannot call undefined

How can i resolve this.Please help.


Solution

  • The Math that is initialized by default not the java system Math. If you want the java's Math use:

    var JavaMath = Java.type("java.lang.Math");
    

    Then you can use all of the math methods. I am surprised Nashorn doesn't provide the javascript Math Object, which would have log10.