I have precompiled Lua script with ScriptEngine.
private void preCompile(){
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("luaj");
if(engine instanceof Compilable){
try {
compScript = ((Compilable)engine).compile(scriptContent);
}catch (ScriptException se){
System.err.println(se.getMessage());
}
}else{
System.err.println("Engine can't compile code!");
}
And I can also execute it with eval() function and call the functions in the Script with LuaFunction.invoke(LuaValue).
public Object callFunction(String funcName, Object[] args){
preCompile();
Bindings script_bindings = new SimpleBindings();
try{
compScript.eval(script_bindings);
LuaFunction luafunc = (LuaFunction)script_bindings.get(funcName);
LuaValue[] luaValues = new LuaValue[args.length];
for(int i = 0; i < args.length; ++i){
luaValues[i] = CoerceJavaToLua.coerce(args[i]);
}
result = luafunc.invoke(luaValues);
}catch (ScriptException se){
System.out.println(se.getMessage());
}
return result;
}
Here Is The Problem:
I can executed script with Java API, but what I want to do is making a custom environment by using Global.
so I create Global object and load needed libs like this:
private void LoadScript(){
globals = new Globals();
globals.load(new JseBaseLib());
globals.load(new PackageLib());
globals.load(new StringLib());
globals.load(new Bit32Lib());
globals.load(new TableLib());
LoadState.install(globals);
LuaC.install(globals);
Now I just don't know how to link 'globals' to the compiled file(compScript). I have tried the global compiled function
Prototype chunk = globals.compilePrototype(new StringReader(script), "script");
chunk.call()
can be used to execute script, but I still don't know how to call the functions(with or without arguments) in script by 'chunk' or 'compScript' in my custom 'globals' environment.
In addition, is globals.load()
function compile script file? I just want to compile script once and reuse it.