Reputation: 3
I've come across an issue with LuaJ not accepting an LuaValue as an argument when the Java code specifically asks for an LuaValue.
public void registerEvent(LuaValue id, String event, String priority,
LuaValue callback)
{
if(!(id instanceof LuaTable))
{
throw new RuntimeException("id must be an LuaTable");
}
EventDispatcher.addHandler(id, event, priority, callback);
}
Ideally, this would allow the code in Lua to simply read like so...
function main(this)
this.modName="Some Mod"
this.lastX = 0
hg.both.registerEvent(this, "inputcapturedevent", "last", eventRun)
end
function eventRun(this, event)
this.lastX += event.getX()
end
Sadly, this simple gives an error that it expects userdata, but got a table.
org.luaj.vm2.LuaError: script:4 bad argument: userdata expected, got table
The value of "this" is the same LuaTable in both cases, but because the method registerEvent is added via CoerceJavaToLua.coerce(...) it believes it wants a java Object instead of realising it really wants an LuaVale.
So my question is this. Is there a better way around this that allows me to use the same function from both Java and Lua? And thanks for your time if you read it all the way here :)
Upvotes: 0
Views: 640
Reputation: 201
The error you are getting is probably a red herring and may be due to the way you are binding the "registerEvent" function into the value of "hg.both". Possibly you just need to use the method syntax instead, such as
hg.both:registerEvent(this, "inputcapturedevent", "last", eventRun)
If you want to use the dot syntax hg.both.registerEvent, then using VarArgFunction and implementing invoke() may be a more direct way to implement this. In this example, Both.registerEvent is a plain variable that is a VarArgFunction.
public static class Both {
public static VarArgFunction registerEvent = new VarArgFunction() {
public Varargs invoke(Varargs args) {
LuaTable id = args.checktable(1);
String event = args.tojstring(2);
String priority = args.tojstring(3);
LuaValue callback = args.arg(4);
EventDispatcher.addHandler(id, event, priority, callback);
return NIL;
}
};
}
public static void main(String[] args) throws ScriptException {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("luaj");
Bindings sb = engine.createBindings();
String fr =
"function main(this);" +
" this.modName='Some Mod';" +
" this.lastX = 0;" +
" hg.both.registerEvent(this, 'inputcapturedevent', 'last', eventRun);" +
"end;";
System.out.println(fr);
CompiledScript script = ((Compilable) engine).compile(fr);
script.eval(sb);
LuaFunction mainFunc = (LuaFunction) sb.get("main");
LuaTable hg = new LuaTable();
hg.set("both", CoerceJavaToLua.coerce(Both.class));
sb.put("hg", hg);
LuaTable library = new LuaTable();
mainFunc.call(CoerceJavaToLua.coerce(library));
}
Upvotes: 1