lua-users home
lua-l archive

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


But why bother putting it in the preload table if you then immediately load it
using C code? The idea of the preload table is so you can have C libraries compiled into
the runtime but which only get loaded into the Lua environment if called for by
the script. If you load it right off, you should load it like any of the standard
libraries i.e. by just executing its loader function.

I use another loop:

const luaL_Reg *lib = gloads;
for (; lib->func; lib++) {
	lua_pushcfunction(L, lib->func);
	lua_pushstring(L, lib->name);
	lua_call(L, 1, 0);
};

For the stuff I want to be available without a require statement in Lua.

The advantage of this is it is "data driven" - you manage your libraries just by changing
the two luaL_Reg tables.

> -----Original Message-----
> From: lua-bounces@bazar2.conectiva.com.br [mailto:lua-
> bounces@bazar2.conectiva.com.br] On Behalf Of Jerome Vuarand
> Sent: 03 September 2009 13:23
> To: Lua list
> Subject: Re: Wishlists and Modules (was [ANN] libmc)
> 
> 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;
> }