4

I use 5.2 for learning recently, what I want to try like this:

Step 1, build a c module for 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;
}

I compile and link it with liblua.a, and I'm sure it works well in lua script like "require("tool") tool.add(1, 2)"

Step 2, I write another C program that wants to require my c module in step 1 like this:

#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;
}

I also compile & link with liblua.a, but error occurs when I run it: "require_fail=multiple Lua VMs detected"

Someone's blog said that in lua5.2, you should link c module and c host program both dynamicly, but not staticly.

is there someone that has the same problem, or is there somehing wrong in my code, thanks.

NOTICE:

the problem has been solved by compile main program with -Wl,-E, thanks a lot for all your help ^^.

3
  • I think you have answered your own question: yes, you should link the module dynamically!
    – prapin
    Jan 8, 2013 at 11:32
  • as we know, the origin makefile doesn't support compiling dynamicly, the program core dump when i modify the makefile and recompile lua, what can i do Jan 8, 2013 at 13:20
  • 1
    "the program core dump when i modify the makefile and recompile lua, what can i do" Post about that problem, rather than the broken result of your workaround.
    – Mud
    Jan 8, 2013 at 16:55

1 Answer 1

5

Don't link your C module with liblua.a when you create a .so from it. For examples, see my page of Lua libraries: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/ . You can link liblua.a statically into your main program but you have to export its symbols by adding -Wl,-E at link time. That's how the Lua interpreter is built in Linux.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.