我想将 Java 类的实例作为用户数据返回到我的 lua 脚本。是否可以从 lua 访问此实例的属性和功能?
像这样
local car = Car.getNew()
print(car.hasHonked)
car:honk()
print(car.hasHonked)
这是我解决问题的尝试
Java(缩短)
public class CarModule extends TwoArgFunction {
String moduleName = "Car";
public LuaValue call(LuaValue modname, LuaValue env) {
LuaValue library = new LuaTable();
library.set("getNew", new getNew());
env.set(moduleName, library);
return library;
}
static class getNew extends ZeroArgFunction {
@Override
public LuaValue call() {
return LuaValue.userdataOf(new Car());
}
}
}
public class Car {
private int count;
@Override
public String toString() {
return "Hello World";
}
public void honk() {
count++;
}
public int getHonks() {
return count;
}
}
lua
local car = Car.getNew()
print(car) -- foo.bar.lua.module.CarModule$Car@1ef7fe8e
print(type(car)) -- = userdata
print(car.honk) -- = nil
print(car.getHonks) -- = nil
print(car:honk) -- = LuaError: function arguments expected
print(car:getHonks) -- = LuaError: function arguments expected
print(tostring(car)) -- = Hello World
car:honk() -- = LuaError: attempt to call nil
car:getHonks() -- = LuaError: attempt to call nil
编辑:
在这里找到了答案
代替
return LuaValue.userdataOf(new Car());
我必须使用
return CoerceJavaToLua.coerce(new Car());