繁体   English   中英

LUAJ强制Java对象将不接受LuaValue参数

[英]LUAJ Coerced Java object won't accept LuaValue argument

当Java代码专门要求提供LuaValue时,我遇到了LuaJ不接受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);
}

理想情况下,这将使Lua中的代码像这样简单地阅读...

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

可悲的是,这个简单的错误给出了一个期望的用户数据,但是却得到了一个表。

org.luaj.vm2.LuaError: script:4 bad argument: userdata expected, got table

在这两种情况下,“ this”的值都是相同的LuaTable,但是由于方法registerEvent是通过CoerceJavaToLua.coerce(...)添加的,因此它认为它想要一个Java对象,而不是意识到它确实需要一个LuaVale。

所以我的问题是这个。 有没有更好的方法可以让我使用Java和Lua的相同功能? 如果您一直在这里阅读它,谢谢您的时间:)

您收到的错误可能是红色鲱鱼,并且可能是由于您将“ 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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM