LuaJ错误的返回类型转换

时间:2016-01-13 14:38:14

标签: types lua luaj multiple-return-values

我有以下代码,使用LuaJ无法正常工作。

/* imports ommited */
public class LuaTest {

public static String name = "script";
public static String script =
    "function numbers()"
    + "   return 200, 100"
    + "   end "
    + "object = obj:new() " 
    + "x = numbers() " 
    + "print(x)" 
    + "print(\"x type = \" .. type(x))" 
    + "z = object:numbers()" 
    + "print(z)" 
    + "print(\"z type = \" .. type(z))";

public static void main(String[] args) throws Exception {
    LuaValue myObject = CoerceJavaToLua.coerce(new MyClass());
    Globals globals = JsePlatform.standardGlobals();
    globals.set("obj", myObject);
    LuaValue chunk = globals.load(script);
    chunk.call();
}
}

public class MyClass {

public VarArgFunction numbers() {
    return new MultiValueReturn(LuaValue.valueOf(200), LuaValue.valueOf(100));
}

public class MultiValueReturn extends VarArgFunction {
    private LuaValue[] args;

    public MultiValueReturn(LuaValue p1, LuaValue p2) {
        this.args = new LuaValue[2];
        this.args[0] = p1;
        this.args[1] = p2;
    }

    @Override
    public LuaValue arg(int i) {
        if (i <= this.args.length) {
            return args[i - 1];
        }
        return null;
    }
}
}

请注意,我的Lua脚本调用两个不同的函数,称为“数字”,一个来自强制对象,另一个来自本机Lua。两者都应该以相同的方式返回两个值,从中只使用第一个值。

执行输出是:

200
x type = number
200
z type = function

但我希望它是这样的:

200
x type = number
200
z type = number

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

您的课程正在被强制执行,但多个返回值具有挑战性。

制作&#39;号码&#39;一个VarArgFunction类型的字段,而是实现VarArgFunction.invoke()。

然后lua的 object.numbers 映射到Java的 MyClass.numbers 的值,这是一个VarArgFunction,因此可以调用使用多个参数并返回多个返回值。

public class LuaTest {

    public static String name = "script";
    public static String script =
        "function numbers()"
        + "   return 200, 100"
        + "   end "
        + "object = obj:new() " 
        + "x = numbers() " 
        + "print(x)" 
        + "print(\"x type = \" .. type(x))" 
        + "z = object:numbers()" 
        + "print(z)" 
        + "print(\"z type = \" .. type(z))";

    public static void main(String[] args) throws Exception {
        LuaValue myObject = CoerceJavaToLua.coerce(new MyClass());
        Globals globals = JsePlatform.standardGlobals();
        globals.set("obj", myObject);
        LuaValue chunk = globals.load(script);
        chunk.call();
    }

    public static class MyClass {

        public VarArgFunction numbers = new VarArgFunction() {
            @Override
            public Varargs invoke(Varargs args) {
                return varargsOf(valueOf(200), valueOf(100));
            }
        };
    }
}