Common Embedding Techniques Cheat Sheet
This document contains quick code snippets for common script embedding operations. The idea for this document came from the paper Embedding APIs of Java-Based Scripting Engines available at: http://pnuts.org/~tomatsu/embedding.html
Evaluate an Expression Reading from a String
ScriptEnvironment env = script.getScriptEnvironment();
Scalar value = env.evaluateExpression("3 * (10 / 2)");
Execute a Script Reading from a Stream (without creating a String)
ScriptLoader loader = new ScriptLoader();
ScriptInstance script = loader.loadScript("name", inputStream);
script.runScript();
Catch a Runtime Script Error
public class Watchdog implements RuntimeWarningWatcher
{
public void processScriptWarning(ScriptWarning warning)
{
String message = warning.getMessage();
int lineNo = warning.getLineNumber();
String script = warning.getNameShort(); // name of script
}
}
script.addWarningWatcher(new Watchdog());
Catch a Syntax Error when loading a Script
try
{
ScriptInstance script;
script = loader.loadScript("name", inputStream);
}
catch (YourCodeSucksException ex)
{
Iterator i = ex.getErrors().iterator();
while (i.hasNext())
{
SyntaxError error = (SyntaxError)i.next();
String description = error.getDescription();
String code = error.getCodeSnippet();
int lineNumber = error.getLineNumber();
}
}
Set/Get a Variable without Parsing
script.getScriptVariables().putScalar("$var", SleepUtils.getScalar("value"));
Scalar value = script.getScriptVariables().getScalar("$var");
Call a function/method without parsing scripts
script.callFunction("&functionName", new Stack());