I want to return an instance of a Java class as userdata to my lua script. Would it be possible to access properties and functions of this instance from lua?
Like so
local car = Car.getNew()
print(car.hasHonked)
car:honk()
print(car.hasHonked)
That's my attempt to solve the problem
Java (shortened)
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
Edit:
Found the answer here
Instead of
return LuaValue.userdataOf(new Car());
I have to use
return CoerceJavaToLua.coerce(new Car());