gpt4 book ai didi

java - 从Luaj继承Java类

转载 作者:太空宇宙 更新时间:2023-11-04 14:27:03 30 4
gpt4 key购买 nike

在 Luaj 中,是否可以让 Lua 类扩展 Java 类?我尝试在绑定(bind)类上使用 getmetatable() ,但显然它返回 nil 。

这里,Wizard是绑定(bind)到Lua的Java类,SetupWizard是我要继承Wizard的Lua类。

function SetupWizard:new()
local self = setmetatable({}, getmetatable(Wizard))
return self
end

__index 分配给 Wizard 的值也不起作用。

SetupWizard 定义:

SetupWizard = {
host = nil,
user = nil,
password = nil,
database = nil,
mySqlTables = {
users = nil,
},
}
SetupWizard.__index = Wizard

... SetupWizard methods here

最佳答案

LuaJ 在如何处理诸如从 java 导入类之类的事情方面相当灵活。您尚未指定如何完成此操作,因此我假设您已通过创建 library of Java Functions 来完成此操作。作为构建您可以需要的模块的桥梁(使用 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 类,请随时在对此答案的评论中进行澄清。

关于java - 从Luaj继承Java类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563900/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com