2013-01-08 12 views
4

我用5.2最近的學習,我想嘗試這樣的東西:lua5.2的錯誤:多個虛擬機的Lua檢測

步驟1,建立交流模塊LUA:

#include "lua.h" 
#include "lauxlib.h" 
#include "lualib.h" 
#include <stdlib.h> 

static int add(lua_State *L) { 
    int x = luaL_checkint(L, -2); 
    int y = luaL_checkint(L, -1); 
    lua_pushinteger(L, x + y); 
    return 1; 
} 

static const struct luaL_Reg reg_lib[] = { 
    {"add", add} 
}; 

int luaopen_tool(lua_State *L) { 
    luaL_newlib(L, reg_lib); 
    lua_setglobal(L, "tool"); 
    return 0; 
} 

我編譯鏈接它與liblua.a,並且我確信它在lua腳本中運行良好,如「require(」tool「)tool.add(1,2)」

第2步,我編寫另一個C程序,在步驟1中需要我的c模塊,如下所示:

#include "lua.h" 
#include "lauxlib.h" 
#include "lualib.h" 
#include <stdlib.h> 

int main(int argc, char* const argv[]) { 
    lua_State *L = luaL_newstate(); 
    luaL_requiref(L, "base", luaopen_base, 1); 
    luaL_requiref(L, "package", luaopen_package, 1); 
    lua_getglobal(L, "require"); 
    if (!lua_isfunction(L, -1)) { 
     printf("require not found\n"); 
     return 2; 
    } 
    lua_pushstring(L, "tool"); 
    if (lua_pcall(L, 1, 1, 0) != LUA_OK) { 
     printf("require_fail=%s\n", lua_tostring(L, -1)); 
     return 3; 
    } 
    lua_getfield(L, -1, "add"); 
    lua_pushinteger(L, 2); 
    lua_pushinteger(L, 3); 
    lua_pcall(L, 2, 1, 0); 
    int n = luaL_checkint(L, -1); 
    printf("n=%d\n", n); 
    return 0; 
} 

我也編譯liblua.a &鏈接,但發生錯誤,當我運行它: 「require_fail =多個虛擬機的Lua檢測」

某人的博客中表示,在lua5.2,你應該鏈接C模塊中和c主機動態編程,但不是靜態編程。

是否有人遇到同樣的問題,或者在我的代碼中存在錯誤,謝謝。

注意:

問題已經與輪候冊,-E解決了編譯主程序,非常感謝你的幫助^^。

+0

我想你已經回答了你自己的問題:是的,你應該動態鏈接模塊! – prapin

+0

我們知道,原始makefile不支持動態編譯,當我修改生成文件並重新編譯lua時,程序核心轉儲,我能做什麼 –

+1

「程序核心轉儲當我修改生成文件並重新編譯lua時,我可以做什麼做「發佈有關*的問題,而不是你的解決方法的破壞結果。 – Mud

回答

5

當您從其創建.so時,請勿將您的C模塊與liblua.a鏈接。有關示例,請參閱我的Lua庫頁面:http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/。您可以將liblua.a靜態鏈接到主程序中,但必須在鏈接時添加-Wl,-E以導出其符號。這就是Lua解釋器是如何在Linux中構建的。

+0

非常感謝,我明白了!謝謝 –