2
我想返回一個Java類的實例作爲userdata到我的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;
}
}
盧阿
local car = Car.getNew()
print(car) -- [email protected]
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
編輯:
找到了答案here
而不是
return LuaValue.userdataOf(new Car());
我不得不使用
return CoerceJavaToLua.coerce(new Car());