Search code examples
javaluaembedluaj

LuaJ Import Lua Methods


I'm using LuaJ, and I have a .lua file filled with a bunch of functions. How do I import these functions to use in Java with LuaJ?


Solution

  • One option would be to compile the file into Java code and import that. Another would be to simply invoke the Lua file directly from your Java code using the embeddable interpreter.


    * EDIT *

    There are good examples in the downloaded documentation. To run a script from within Java you would do something like this:

    import java.io.File;
    import java.io.FileReader;
    import java.io.Reader;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    
    public class LuaTest {
        public static void main(String[] args) throws Exception {
            String scriptFilePath = "/Users/developer/work/luaj-2.0.2/examples/lua/hello.lua";
    
            Reader reader = new FileReader(new File(scriptFilePath));
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine e = mgr.getEngineByExtension(".lua");
            Object result = e.eval(reader);
        }
    }
    

    To compile a Lua script into Java source code, you would do something like this:

    java -cp lib/luaj-jse-2.0.2.jar lua2java -s examples/lua -d . hello.lua
    javac -cp lib/luaj-jse-2.0.2.jar hello.java
    

    These examples are pretty much taken from the README.html which you get when you download Luaj. I would highly recommend reading it end to end to get a good grasp of the available functionality.