强制类型转换为Java对象的LUAJ不会接受LuaValue参数。

我遇到了一个问题,LuaJ在Java代码明确要求LuaValue作为参数时,不接受LuaValue作为参数。

理想情况下,Lua中的代码应该像这样简单地写成...

然而,这会导致错误,它期望得到userdata,但得到了table。

"this"的值在两种情况下都是相同的LuaTable,但由于registerEvent方法是通过CoerceJavaToLua.coerce(...)添加的,它认为它想要一个java对象,而没有意识到它实际上想要一个LuaValue。

所以我的问题是这样的:有没有更好的方法让我从Java和Lua都使用相同的函数?如果你一直看到这里了,谢谢你的时间 :)

点赞
用户2556943
用户2556943

你得到的错误可能是一个红鲱鱼,可能是因为你将“registerEvent”函数绑定到“hg.both”的值的方式有问题。可能你只需要使用方法语法,例如

hg.both:registerEvent(this, "inputcapturedevent", "last", eventRun)

如果你想使用点语法_hg.both.registerEvent_,那么使用VarArgFunction并实现invoke()可能是实现这一目的的更直接的方法。在这个例子中,Both.registerEvent是一个普通的变量,它是一个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));
}
2016-01-23 19:05:22