2016-01-13 102 views
0

我有下面的代碼,它不能像我期望的那樣使用LuaJ。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 

我缺少的東西?

回答

0

你的課程被強制執行,但多個返回值具有挑戰性。

使'數字'成爲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)); 
      } 
     }; 
    } 
}