Java-Side Modules
To understand the following, you are expected to know how Lua's require
works.
Classpath Lua Modules
With Java, in many cases you put your resources on the classpath, which may be a path accessible to Lua, or one lying in a JAR.
Of course, it is possible to load any Lua files manually by Class::getResourceAsStream
and then reading it into a (direct) buffer and then Lua::load(buffer, name)
.
Alternatively, we provide a ClassPathLoader
. One just initializes the Lua state by setting a external loader, and then they can forget about the Java side classpath and just require
any classpath Lua modules from Lua.
For more flexibility, just extend ClassPathLoader
or write your own ExternalLoader
.
try (Lua L = new Lua51()) {
L.openLibrary("package");
L.setExternalLoader(new ClassPathLoader());
}
2
3
4
-- Loads classpath:/luajava/luajava-compat.lua
local luajava = require('suite.luajava-compat')
2
Java Method Modules
This provides an approach to loading libraries written in Java, similar to Lua's package.loadlib
. It does the following:
- Split the module name by the last dot (
.
) intoFullyQualifiedClassName.staticMethodName
.- The method is expected to be of the form
public static int method(Lua L);
. See the Javadoc ofJFunction
for more info.
- The method is expected to be of the form
- Call
java.loadlib
to encapsulate the Java static method into a C function to be used in Lua. - We leave the rest to Lua's
require
:require
calls the loader with two arguments:modname
and an extra value.- The extra value is
nil
for LuaJava.
package party.iroiro.luajava.docs;
import party.iroiro.luajava.Lua;
@SuppressWarnings("unused")
public class JavaSideExampleModule {
public static int open(Lua L) {
L.createTable(0, 1);
L.push(l -> {
l.push(1024);
return 1;
});
L.setField(-2, "getNumber");
return 1;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
try (Lua L = new Lua51()) {
L.openLibrary("package");
L.run("local LuaLib = require('party.iroiro.luajava.docs.JavaSideExampleModule.open');" +
"assert(1024 == LuaLib.getNumber())");
}
2
3
4
5
local LuaLibOpen = java.loadlib('party.iroiro.luajava.docs.JavaSideExampleModule', 'open')
assert(1024 == LuaLibOpen().getNumber())
2
Binary Modules
Lua supports dynamically loading binary libraries, which utilizes Lua C API to interact with Lua runtime. A binary library, by its nature, is hardly portable and might not even work across Lua versions. To load binary modules, you will need to invoke LuaNative#loadAsGlobal
manually. See Using Binary Lua Libraries for more info.