LuaJ 在处理诸如从 java 中导入类之类的事情方面相当灵活。你没有指定你是如何做到这一点的,所以我假设你已经通过创建一个Java 函数库作为一个桥梁来构建一个你可以要求 (with require"moduleName"
) 的模块,如下所示:
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.TwoArgFunction;
/*
* When require"module name" is called in luaJ it also searches for java classes with a classname that matches
* the given module name that inherit from LuaFunction and have a default constructor, it then
* calls the method call(LuaValue moduleName, LuaValue globalEnviroment) passing the module name string and
* global environment as LuaValues and returning the return value of this call as it's own.
*
*/
public class Example extends TwoArgFunction{
@Override
public LuaValue call(LuaValue modname, LuaValue globalEnv) {
// Creates a table to place all our functions in
LuaValue table = LuaValue.tableOf();
// Sets the value 'name' in our table to example. This is used in the example function
table.set("name", "example");
// Sets the value 'exampleMethod' in our table to the class of type OneArgFunction
// we created below
table.set("exampleMethod", exampleMethod);
//Finally returns our table. This value is then returned by require.
return table;
}
/* Creates a function that takes one arg, self.
This emulates the creation of a method in lua and can be called,
when added to a table, as table:exampleMethod().
This is possible as in Lua the colon in functions is
Syntactic suger for object.function(object)
*/
OneArgFunction exampleMethod = new OneArgFunction() {
@Override
public LuaValue call(LuaValue self) {
if(self.istable()) {
return self.get("name");
}
return NIL;
}
};
}
这可以在你的 Lua 代码中使用,如下所示:
--Imports the class Wrapper we created
example = require"Example"
--Prints the return value of calling exampleMethod
print("The name of the class is: "..example:exampleMethod())
--And then used as an index like so
example2 = setmetatable({},{__index=example})
example2.name = "example2"
print("The name of the class is: "..example2:exampleMethod())
正如我在答案顶部所说,LuaJ 在如何处理这些事情方面很灵活,这只是我会做的方式。
由于我的声誉,我无法发表评论,询问您如何在 LuaJ 中导入 Java 类,请随时在对此答案的评论中澄清。