New function 'luaL_openselectedlibs'

Makes it easier to start Lua with only some standard libraries.
This commit is contained in:
Roberto Ierusalimschy
2022-12-07 15:12:52 -03:00
parent 0270c204c2
commit d738c8d18b
7 changed files with 85 additions and 83 deletions

51
linit.c
View File

@@ -8,21 +8,6 @@
#define linit_c
#define LUA_LIB
/*
** If you embed Lua in your program and need to open the standard
** libraries, call luaL_openlibs in your program. If you need a
** different set of libraries, copy this file to your project and edit
** it to suit your needs.
**
** You can also *preload* libraries, so that a later 'require' can
** open the library, which is already linked to the application.
** For that, do the following code:
**
** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
** lua_pushcfunction(L, luaopen_modname);
** lua_setfield(L, -2, modname);
** lua_pop(L, 1); // remove PRELOAD table
*/
#include "lprefix.h"
@@ -36,30 +21,44 @@
/*
** these libs are loaded by lua.c and are readily available to any Lua
** program
** Standard Libraries
*/
static const luaL_Reg loadedlibs[] = {
static const luaL_Reg stdlibs[] = {
{LUA_GNAME, luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_COLIBNAME, luaopen_coroutine},
{LUA_TABLIBNAME, luaopen_table},
{LUA_DBLIBNAME, luaopen_debug},
{LUA_IOLIBNAME, luaopen_io},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_TABLIBNAME, luaopen_table},
{LUA_UTF8LIBNAME, luaopen_utf8},
{LUA_DBLIBNAME, luaopen_debug},
{NULL, NULL}
};
LUALIB_API void luaL_openlibs (lua_State *L) {
/*
** require selected standard libraries and add the others to the
** preload table.
*/
LUALIB_API void luaL_openselectedlibs (lua_State *L, int what) {
int mask = 1;
const luaL_Reg *lib;
/* "require" functions from 'loadedlibs' and set results to global table */
for (lib = loadedlibs; lib->func; lib++) {
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
for (lib = stdlibs; lib->func; (lib++, mask <<= 1)) {
if (what & mask) { /* selected? */
luaL_requiref(L, lib->name, lib->func, 1); /* require library */
lua_pop(L, 1); /* remove result from the stack */
}
else { /* add library to PRELOAD table */
lua_pushcfunction(L, lib->func);
lua_setfield(L, -2, lib->name);
}
}
lua_assert((mask >> 1) == LUA_UTF8LIBK);
lua_pop(L, 1); // remove PRELOAD table
}