lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2009/9/3 John Hind <john.hind@zen.co.uk>:
> Or like this:
>
> #include "LuaJHcomlib.h"
> static const luaL_Reg gpreloads[] = {
> //  {"name", luaopen_name},
>    {"com", luaopen_com},
>    {NULL, NULL}
> };
>
> // When setting up the environment ...
>        const luaL_Reg * lib = gpreloads;
>        lua_getglobal(L, "package");
>        lua_getfield(L, -1, "preload");
>        for (; lib->func; lib++) {
>                lua_pushcfunction(L, lib->func);
>                lua_setfield(L, -2, lib->name);
>        };
>        lua_pop(L, 2);

You can also write some helper functions:

void luaL_preload(lua_State* L, const char* modname, lua_CFunction luaopen)
{
  lua_getglobal(L, "package");
  lua_getfield(L, -1, "preload");
  lua_pushcfunction(L, luaopen);
  lua_setfield(L, -2, modname);
  lua_pop(L, 2);
}

void luaL_require(lua_State* L, const char* modname, lua_CFunction luaopen)
{
  luaL_preload(L, modname, luaopen);
  lua_getglobal(L, "require");
  lua_pushstring(L, modname);
  lua_call(L, 1, 0);
}

int main()
{
  lua_State* L = luaL_newstate(L);
  luaL_openlibs(L);
  luaL_preload(L, "name", luaopen_name);
  luaL_require(L, "com", luaopen_com);
  ...
  lua_close(L);
  return 0;
}