Search code examples
clua

Lua C api : How to load lua files defined as modules?


I have the following lua script :

module("modoo",package.seeall)
foo=1
bar={12,34}

Which works fine using the cli, such as :

> dofile "mod_modoo.lua"
> =modoo.foo
1
> =modoo
table: 0x86ce058

As far as I understood, it works like a table, but whenever I try loading it as a table, a nil value is pushed onto the stack. Every other table works normally.

I thought using lua_getglobal wouldn't work with modules, but I couldn't find the proper way to load it either ; how should I do it ?


Solution

  • Load Lua modules with require like lua.c does. See http://www.lua.org/source/5.1/lua.c.html#dolibrary

    static int dolibrary (lua_State *L, const char *name) {
      lua_getglobal(L, "require");
      lua_pushstring(L, name);
      return report(L, docall(L, 1, 1));
    }