Scripting API (JSR 223) を使うと、ユーザのスクリプトを標準API(javax.scriptパッケージ)から実行できるようにスクリプティング・エンジンを埋め込んだJavaアプリを書くことができます。
pnuts.jarとpnuts-jsr223.jarがCLASSPATHに含まれていれば、JSR223用Pnutsエンジンが利用できます。
import javax.script.*;
public class HelloWorld {
public static void main(String[] args) throws Exception {
//Initiate ScriptEngineManager
ScriptEngineManager manager = new ScriptEngineManager();
//Return Pnuts engine by name
ScriptEngine jsengine = manager.getEngineByName("pnuts");
//Execute the HelloWorld script
jsengine.eval(new java.io.FileReader("HelloWorld.pnut"));
}
}
import javax.script.*;
public class CompilableInterface {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine pnutsEngine = manager.getEngineByName("pnuts");
Compilable eng = (Compilable)pnutsEngine;
CompiledScript scr = eng.compile(new java.io.FileReader("CompilableInterface.pnut"));
ScriptEngine e = (ScriptEngine)eng;
//set engine scope namespace
Bindings n = new SimpleBindings();
e.setBindings(n, ScriptContext.ENGINE_SCOPE);
//evaluate compiled script
for (int i=0; i<3; i++) {
n.put("count", new Integer(i));
n.put("currentTime", new Long(System.currentTimeMillis()));
scr.eval();
}
}
}
counter = 0
switch (count) {
case 0: counter = "first time"; break;
case 1: counter = "second time"; break;
case 2: counter = "third time";
}
println("\nRun compiled script, the ", counter)
time = date(currentTime)
println("Current time is ", time)
Pnutsエンジンを設定するには、Pnuts.setDefault(Properties)メソッドで、Pnuts APIがロードされる前に以下のプロパティを必要に応じて設定します。
Property Description Default pnuts.modules エンジンが初期化される時に使用状態になるモジュールをカンマで区切って指定します。 pnuts.tools pnuts.lang.defaultPnutsImpl pnuts.lang.Implementationの実装クラスが指定された場合、それがデフォルトのImplementationになります。 pnuts.compiler.CompilerPnutsImpl pnuts.lang.defaultConfiguration pnuts.lang.Configurationのサブクラスが指定された場合、それがデフォルトのConfigurationになります。 デフォルト値 pnuts.compiler.optimize trueが指定された場合は、Pnutsコンパイラが生成するコードの実行速度が若干速くなります。そのかわり、エラー表示の行番号が表示されなくなります。 false pnuts.compiler.useDynamicProxy trueが指定された場合は、メソッドやコンストラクタの実装として、 Reflection APIではなく、動的に生成するプロキシクラスを使います。JITコンパイラとの組合せにより、メソッドやコンストラクタの呼び出しが若干速くなります。 true pnuts.package.factory 起動時にこのプロパティが指定されていた場合、そのクラスがデフォルトのパッケージ・ファクトリになります。pnuts.lang.PackageFactoryクラスを参照。 デフォルト値
C:\> jrunscript -l pnutsのようにPnutsを利用できます。
別の方法として、Pnutsをインストールしたディレクトリを%PNUTS_HOME%とし、
C:\> jrunscript -J-Djava.ext.dirs=%PNUTS_HOME%\lib;%PNUTS_HOME%\modules -l pnutsを起動してもかまいません。bashのようにaliasの機能があるシェルでは、
alias jrunscript='jrunscript "-J-Djava.ext.dirs=d:/pnuts/lib;d:/pnuts/modules"'のようにaliasを定義しておくと便利かもしれません。
bash$ jrunscript -q Language ECMAScript 0 implemention "Mozilla Rhino" @IMPLEMENTATION.VERSION@ Language Pnuts 1.1 implemention "Pnuts" 1.0 bash$ jrunscript -l pnuts pnuts>