What is the best way to remove or omit a Lua standard library package? For example remove the os library functions in a particular environment. The project in question is building Lua from the source files so I can edit the source, although I would rather do it through the API if possible.
Share
See the file
luaconf.hin the source kit for easy access to most compile-time configuration such as the actual type used forlua_Number.See the file
linit.cin the source kit for the list of core libraries that are loaded by callingluaL_openlibs().Common practice is to copy that file to your application’s source, and modify it to suit your needs, calling that copy’s
luaL_openlibs()in place of the core version. If you are compiling Lua privately and not linking to one of the pre-built binaries of the library, then you can find a method to do the equivalent that suits your needs.Of course, you also don’t need to compile or link to the sources for any library (such as
os, found inloslib.c) that you choose to leave out ofluaL_openlibs().The only library that you probably can’t leave out completely is the base library that provides things like
pairs(),ipairs(),pcall(),tostring(), and lots more that can be really inconvenient to do without. When porting to an environment where some of these are problematic, it is usually a good idea to look closely at its implementation inlbaselib.cand either trim features from it or reimplement them to suit your needs.Edit:
Another approach to including a different list of libraries in the interpreter is to not call
luaL_openlibs()at all. Although provided as a convenience, like all of the auxiliary library,luaL_openlibs()is not mandatory. Instead, explicitly open just the libraries you want.Chapter 5 of the reference manual talks about this:
That last sentence is occasionally the source of trouble, since older versions of Lua did not have that restriction. Each of the individual module’s
luaopen_xxx()functions follows the same protocol used by therequirefunction. It should be passed a single argument: a string containing the name by which the module is known. The exception is the base module, which is passed an empty string because it has no actual name.Here’s a function that creates a new Lua state and opens only the base and package libraries:
It returns the new
lua_Stateon success, orNULLon failure.