简体   繁体   中英

Java method for compiling Lua code with the LuaJ interpreter

http://luaj.org/luaj/README.html

I'm using Luaj to run Lua code in a Java application. I'm getting some really slow results, so I want to try to compile the code before running it to calculate the actual proccesing time of a Lua script.

The problem is - Luaj does show an example how to compile Lua source to Lua or Java bytecode through the command prompt, but it doesn't show me the lines to compile a Lua script with a Java application.

It only shows how to compile AND run a Lua script:

import org.luaj.vm2.*;
import org.luaj.vm2.lib.jse.*;

String script = "examples/lua/hello.lua";
LuaValue _G = JsePlatform.standardGlobals();
_G.get("dofile").call( LuaValue.valueOf(script) );

I want to find the code that would only compile Lua to Lua or Java bytecode and would output a bytecode file.

LuaJ contains a Lua to bytecode compiler. So you can just look at the source code. I have extracted the most relevant portion here.

private void processScript( InputStream script, String chunkname, OutputStream out ) throws IOException {
    try {
        // create the chunk
        Prototype chunk = LuaC.instance.compile(script, chunkname);

        // list the chunk
        if (list)
            Print.printCode(chunk);

        // write out the chunk
        if (!parseonly) {
            DumpState.dump(chunk, out, stripdebug, numberformat, littleendian);
        }

    } catch ( Exception e ) {
        e.printStackTrace( System.err );
    } finally {
        script.close();
    }
}

Keep in mind that you can only really rely on byte code being compatible with the implementation of Lua that produced it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM