[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Quality-of-Life patches
- From: Sean Conner <sean@...>
- Date: Fri, 25 Feb 2022 02:49:09 -0500
It was thus said that the Great Olexa Bilaniuk once stated:
> I have therefore contrived to include the entire contents of re.lua as
> a const char[] and statically link the entire contents of LPeg's
> compiled C code. I then add a "static searcher" that keys off the
> requested module, and if equal to "lpeg" for instance it invokes
> luaopen_lpeg(), or if equal to "re" loads the code string containing
> the body of re.lua. This is made fairly easy with GNU ld linker
> scripts.
>
> The resulting Lua interpreter therefore carries within itself a
> self-contained copy of LPeg, which it uses in preference to any
> locally-installed copy (and this is fine, since LPeg hasn't changed
> anytime recently), and it also does not probe the filesystem for it
> (because the static searcher has higher priority than the Lua, C and
> Croot searchers).
>
> Is there a better way to go about this you'd recommend?
I wrote a custom Lua interpreter for work that includes all the modules we
use in a single executable. I did not modify the Lua code to do this, but I
do have the following code:
/*-------------------------------------------
; Load the standand Lua modules into memory
;--------------------------------------------*/
luaL_openlibs(L);
/*------------------------------------------------------------------
; preload is a luaL_Reg array of the C modules entry point. This
; loads them into the preload array that is searched first for Lua
; modules.
;-------------------------------------------------------------------*/
lua_getglobal(L,"package");
lua_getfield(L,-1,"preload");
luaL_setfuncs(L,preload,0);
/*-------------------------------------------------------------------
; I then add a custom searcher into package.searchers (or
; package.loaders if Lua 5.1) into slot 2, moving the the remaining
; entries up one. So the first searcher is still the default Lua
; searcher that goes through package.preload, then our custom
; loader, then the remaining default searchers. The custom loader
; will load a Lua module written in Lua and stored in the
; executable. In my case, the modules are compressed using libz,
; but that's an implementation detail.
;--------------------------------------------------------------------*/
lua_getglobal(L,"package");
lua_getfield(L,-1,"searchers");
for (lua_Integer i = lua_objlen(L,-1) + 1 ; i > 1 ; i--)
{
lua_rawgeti(L,-1,i - 1);
lua_rawseti(L,-2,i);
}
lua_pushinteger(L,2);
lua_pushcfunction(L,preload_lualoader);
lua_settable(L,-3);
lua_pop(L,4);
I use this method to include over 30 modules written in C, and over 30
other modules written in Lua. This mixture includes both custom modules
related to work, as well as third party libraries (such as lpeg and re).
And it doesn't require modifying the Lua sources to do so.
-spc