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?
LuaJ Import Lua Methods
3k views Asked by Anonymous At
2
There are 2 answers
0
On
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
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:
To compile a Lua script into Java source code, you would do something like this:
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.