2013-06-11 59 views
0

傳遞字符串ARG到Lua方法與LuaJava我有在Java字符串定義一個Lua函數,我想傳遞一個字符串ARG在AndroLua

String luaCode = "function hello(name) return 'Hello ' + name +'!' end"; 

Executng代碼

public String runGreetingFromLua(String src, String arg) throws LuaException { 
    L = LuaStateFactory.newLuaState(); 
    L.openLibs(); 
    L.setTop(0); 
    int ok = L.LloadString(src); 
    if (ok == 0) { 
     L.getGlobal("debug"); 
     L.getField(-1, "traceback"); 
     L.remove(-2); 
     L.insert(-2); 
     L.getGlobal("hello"); 
     L.pushString(arg); 
     ok = L.pcall(1, 0, -2); 
     if (ok == 0) { 
      String res = output.toString(); 
      output.setLength(0); 
      return res; 
     } 
    } 
    throw new LuaException(errorReason(ok) + ": " + L.toString(-1)); 
} 

獲取Unknown error 5: error in error handling

我對lua和luajava完全陌生,我敢肯定,這個簡單的例子並不能理解LauState對象是如何工作的,java文檔並不令人驚訝(或者我不知道一些非常新手)。如果我從lua代碼中調用hello函數並使用print方法,我能夠獲得返回值。我使用的是Android設備上執行AndroLua

回答

0

管理通過去除一些錯誤處理代碼中,似乎干擾luajava例子指出和交換呼叫L.LLloadStringL.LdoString(src);L.pcallL.call得到這個工作。

public String runLuaHello(String src, String arg) throws LuaException { 
    //init 
    L = LuaStateFactory.newLuaState(); 
    L.openLibs(); 
    L.setTop(0); 
    //load the lua source code 
    int ok = L.LdoString(src); 
    if (ok == 0) { 
     //don't quite understand why it's getGlobal? but here you set the method name 
     L.getGlobal("hello"); 
     //send the arg to lua 
     L.pushString(arg); 
     //this specifies 1 arg and 1 result 
     L.call(1, 1); 
     //get the result 
     String result = L.toString(-1); 
     //pop the result off the stack 
     L.pop(1); 
     return result; 
    } 
    throw new LuaException(errorReason(ok) + ": " + L.toString(-1)); 
} 
+0

你有沒有代碼來實現使用Lua的GUI? – User3

+0

恐怕不是,而且tbh多年來一直沒有在Android上看過lua。 – scottyab