سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

I was looking around to solve this same problem myself and although this question was from January hopefully this post will help others looking for help.

test.java:

import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.JsePlatform;

public class test
{
    public static void main(String[] args)
    {
        //run the lua script defining your function
        LuaValue _G = JsePlatform.standardGlobals();
        _G.get("dofile").call( LuaValue.valueOf("./test.lua"));

        //call the function MyAdd with two parameters 5, and 5
        LuaValue MyAdd = _G.get("MyAdd");
        LuaValue retvals = MyAdd.call(LuaValue.valueOf(5), LuaValue.valueOf(5));

        //print out the result from the lua function
        System.out.println(retvals.tojstring(1));
    }
}

test.lua:

function MyAdd( num1, num2 )
    return num1 + num2
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top