lua

A copy of the Lua development repository
Log | Files | Refs | README

loadlib.c (22543B)


      1 /*
      2 ** $Id: loadlib.c $
      3 ** Dynamic library loader for Lua
      4 ** See Copyright Notice in lua.h
      5 **
      6 ** This module contains an implementation of loadlib for Unix systems
      7 ** that have dlfcn, an implementation for Windows, and a stub for other
      8 ** systems.
      9 */
     10 
     11 #define loadlib_c
     12 #define LUA_LIB
     13 
     14 #include "lprefix.h"
     15 
     16 
     17 #include <stdio.h>
     18 #include <stdlib.h>
     19 #include <string.h>
     20 
     21 #include "lua.h"
     22 
     23 #include "lauxlib.h"
     24 #include "lualib.h"
     25 #include "llimits.h"
     26 
     27 
     28 /*
     29 ** LUA_CSUBSEP is the character that replaces dots in submodule names
     30 ** when searching for a C loader.
     31 ** LUA_LSUBSEP is the character that replaces dots in submodule names
     32 ** when searching for a Lua loader.
     33 */
     34 #if !defined(LUA_CSUBSEP)
     35 #define LUA_CSUBSEP		LUA_DIRSEP
     36 #endif
     37 
     38 #if !defined(LUA_LSUBSEP)
     39 #define LUA_LSUBSEP		LUA_DIRSEP
     40 #endif
     41 
     42 
     43 /* prefix for open functions in C libraries */
     44 #define LUA_POF		"luaopen_"
     45 
     46 /* separator for open functions in C libraries */
     47 #define LUA_OFSEP	"_"
     48 
     49 
     50 /*
     51 ** key for table in the registry that keeps handles
     52 ** for all loaded C libraries
     53 */
     54 static const char *const CLIBS = "_CLIBS";
     55 
     56 #define LIB_FAIL	"open"
     57 
     58 
     59 #define setprogdir(L)           ((void)0)
     60 
     61 
     62 /* cast void* to a Lua function */
     63 #define cast_Lfunc(p)	cast(lua_CFunction, cast_func(p))
     64 
     65 
     66 /*
     67 ** system-dependent functions
     68 */
     69 
     70 /*
     71 ** unload library 'lib'
     72 */
     73 static void lsys_unloadlib (void *lib);
     74 
     75 /*
     76 ** load C library in file 'path'. If 'seeglb', load with all names in
     77 ** the library global.
     78 ** Returns the library; in case of error, returns NULL plus an
     79 ** error string in the stack.
     80 */
     81 static void *lsys_load (lua_State *L, const char *path, int seeglb);
     82 
     83 /*
     84 ** Try to find a function named 'sym' in library 'lib'.
     85 ** Returns the function; in case of error, returns NULL plus an
     86 ** error string in the stack.
     87 */
     88 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym);
     89 
     90 
     91 
     92 
     93 #if defined(LUA_USE_DLOPEN)	/* { */
     94 /*
     95 ** {========================================================================
     96 ** This is an implementation of loadlib based on the dlfcn interface,
     97 ** which is available in all POSIX systems.
     98 ** =========================================================================
     99 */
    100 
    101 #include <dlfcn.h>
    102 
    103 
    104 static void lsys_unloadlib (void *lib) {
    105   dlclose(lib);
    106 }
    107 
    108 
    109 static void *lsys_load (lua_State *L, const char *path, int seeglb) {
    110   void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
    111   if (l_unlikely(lib == NULL))
    112     lua_pushstring(L, dlerror());
    113   return lib;
    114 }
    115 
    116 
    117 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
    118   lua_CFunction f = cast_Lfunc(dlsym(lib, sym));
    119   if (l_unlikely(f == NULL))
    120     lua_pushstring(L, dlerror());
    121   return f;
    122 }
    123 
    124 /* }====================================================== */
    125 
    126 
    127 
    128 #elif defined(LUA_DL_DLL)	/* }{ */
    129 /*
    130 ** {======================================================================
    131 ** This is an implementation of loadlib for Windows using native functions.
    132 ** =======================================================================
    133 */
    134 
    135 #include <windows.h>
    136 
    137 
    138 /*
    139 ** optional flags for LoadLibraryEx
    140 */
    141 #if !defined(LUA_LLE_FLAGS)
    142 #define LUA_LLE_FLAGS	0
    143 #endif
    144 
    145 
    146 #undef setprogdir
    147 
    148 
    149 /*
    150 ** Replace in the path (on the top of the stack) any occurrence
    151 ** of LUA_EXEC_DIR with the executable's path.
    152 */
    153 static void setprogdir (lua_State *L) {
    154   char buff[MAX_PATH + 1];
    155   char *lb;
    156   DWORD nsize = sizeof(buff)/sizeof(char);
    157   DWORD n = GetModuleFileNameA(NULL, buff, nsize);  /* get exec. name */
    158   if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
    159     luaL_error(L, "unable to get ModuleFileName");
    160   else {
    161     *lb = '\0';  /* cut name on the last '\\' to get the path */
    162     luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);
    163     lua_remove(L, -2);  /* remove original string */
    164   }
    165 }
    166 
    167 
    168 
    169 
    170 static void pusherror (lua_State *L) {
    171   int error = GetLastError();
    172   char buffer[128];
    173   if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
    174       NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL))
    175     lua_pushstring(L, buffer);
    176   else
    177     lua_pushfstring(L, "system error %d\n", error);
    178 }
    179 
    180 static void lsys_unloadlib (void *lib) {
    181   FreeLibrary((HMODULE)lib);
    182 }
    183 
    184 
    185 static void *lsys_load (lua_State *L, const char *path, int seeglb) {
    186   HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
    187   (void)(seeglb);  /* not used: symbols are 'global' by default */
    188   if (lib == NULL) pusherror(L);
    189   return lib;
    190 }
    191 
    192 
    193 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
    194   lua_CFunction f = cast_Lfunc(GetProcAddress((HMODULE)lib, sym));
    195   if (f == NULL) pusherror(L);
    196   return f;
    197 }
    198 
    199 /* }====================================================== */
    200 
    201 
    202 #else				/* }{ */
    203 /*
    204 ** {======================================================
    205 ** Fallback for other systems
    206 ** =======================================================
    207 */
    208 
    209 #undef LIB_FAIL
    210 #define LIB_FAIL	"absent"
    211 
    212 
    213 #define DLMSG	"dynamic libraries not enabled; check your Lua installation"
    214 
    215 
    216 static void lsys_unloadlib (void *lib) {
    217   (void)(lib);  /* not used */
    218 }
    219 
    220 
    221 static void *lsys_load (lua_State *L, const char *path, int seeglb) {
    222   (void)(path); (void)(seeglb);  /* not used */
    223   lua_pushliteral(L, DLMSG);
    224   return NULL;
    225 }
    226 
    227 
    228 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
    229   (void)(lib); (void)(sym);  /* not used */
    230   lua_pushliteral(L, DLMSG);
    231   return NULL;
    232 }
    233 
    234 /* }====================================================== */
    235 #endif				/* } */
    236 
    237 
    238 /*
    239 ** {==================================================================
    240 ** Set Paths
    241 ** ===================================================================
    242 */
    243 
    244 /*
    245 ** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
    246 ** variables that Lua check to set its paths.
    247 */
    248 #if !defined(LUA_PATH_VAR)
    249 #define LUA_PATH_VAR    "LUA_PATH"
    250 #endif
    251 
    252 #if !defined(LUA_CPATH_VAR)
    253 #define LUA_CPATH_VAR   "LUA_CPATH"
    254 #endif
    255 
    256 
    257 
    258 /*
    259 ** return registry.LUA_NOENV as a boolean
    260 */
    261 static int noenv (lua_State *L) {
    262   int b;
    263   lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
    264   b = lua_toboolean(L, -1);
    265   lua_pop(L, 1);  /* remove value */
    266   return b;
    267 }
    268 
    269 
    270 /*
    271 ** Set a path. (If using the default path, assume it is a string
    272 ** literal in C and create it as an external string.)
    273 */
    274 static void setpath (lua_State *L, const char *fieldname,
    275                                    const char *envname,
    276                                    const char *dft) {
    277   const char *dftmark;
    278   const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX);
    279   const char *path = getenv(nver);  /* try versioned name */
    280   if (path == NULL)  /* no versioned environment variable? */
    281     path = getenv(envname);  /* try unversioned name */
    282   if (path == NULL || noenv(L))  /* no environment variable? */
    283     lua_pushexternalstring(L, dft, strlen(dft), NULL, NULL);  /* use default */
    284   else if ((dftmark = strstr(path, LUA_PATH_SEP LUA_PATH_SEP)) == NULL)
    285     lua_pushstring(L, path);  /* nothing to change */
    286   else {  /* path contains a ";;": insert default path in its place */
    287     size_t len = strlen(path);
    288     luaL_Buffer b;
    289     luaL_buffinit(L, &b);
    290     if (path < dftmark) {  /* is there a prefix before ';;'? */
    291       luaL_addlstring(&b, path, ct_diff2sz(dftmark - path));  /* add it */
    292       luaL_addchar(&b, *LUA_PATH_SEP);
    293     }
    294     luaL_addstring(&b, dft);  /* add default */
    295     if (dftmark < path + len - 2) {  /* is there a suffix after ';;'? */
    296       luaL_addchar(&b, *LUA_PATH_SEP);
    297       luaL_addlstring(&b, dftmark + 2, ct_diff2sz((path + len - 2) - dftmark));
    298     }
    299     luaL_pushresult(&b);
    300   }
    301   setprogdir(L);
    302   lua_setfield(L, -3, fieldname);  /* package[fieldname] = path value */
    303   lua_pop(L, 1);  /* pop versioned variable name ('nver') */
    304 }
    305 
    306 /* }================================================================== */
    307 
    308 
    309 /*
    310 ** return registry.CLIBS[path]
    311 */
    312 static void *checkclib (lua_State *L, const char *path) {
    313   void *plib;
    314   lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
    315   lua_getfield(L, -1, path);
    316   plib = lua_touserdata(L, -1);  /* plib = CLIBS[path] */
    317   lua_pop(L, 2);  /* pop CLIBS table and 'plib' */
    318   return plib;
    319 }
    320 
    321 
    322 /*
    323 ** registry.CLIBS[path] = plib        -- for queries
    324 ** registry.CLIBS[#CLIBS + 1] = plib  -- also keep a list of all libraries
    325 */
    326 static void addtoclib (lua_State *L, const char *path, void *plib) {
    327   lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
    328   lua_pushlightuserdata(L, plib);
    329   lua_pushvalue(L, -1);
    330   lua_setfield(L, -3, path);  /* CLIBS[path] = plib */
    331   lua_rawseti(L, -2, luaL_len(L, -2) + 1);  /* CLIBS[#CLIBS + 1] = plib */
    332   lua_pop(L, 1);  /* pop CLIBS table */
    333 }
    334 
    335 
    336 /*
    337 ** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib
    338 ** handles in list CLIBS
    339 */
    340 static int gctm (lua_State *L) {
    341   lua_Integer n = luaL_len(L, 1);
    342   for (; n >= 1; n--) {  /* for each handle, in reverse order */
    343     lua_rawgeti(L, 1, n);  /* get handle CLIBS[n] */
    344     lsys_unloadlib(lua_touserdata(L, -1));
    345     lua_pop(L, 1);  /* pop handle */
    346   }
    347   return 0;
    348 }
    349 
    350 
    351 
    352 /* error codes for 'lookforfunc' */
    353 #define ERRLIB		1
    354 #define ERRFUNC		2
    355 
    356 /*
    357 ** Look for a C function named 'sym' in a dynamically loaded library
    358 ** 'path'.
    359 ** First, check whether the library is already loaded; if not, try
    360 ** to load it.
    361 ** Then, if 'sym' is '*', return true (as library has been loaded).
    362 ** Otherwise, look for symbol 'sym' in the library and push a
    363 ** C function with that symbol.
    364 ** Return 0 and 'true' or a function in the stack; in case of
    365 ** errors, return an error code and an error message in the stack.
    366 */
    367 static int lookforfunc (lua_State *L, const char *path, const char *sym) {
    368   void *reg = checkclib(L, path);  /* check loaded C libraries */
    369   if (reg == NULL) {  /* must load library? */
    370     reg = lsys_load(L, path, *sym == '*');  /* global symbols if 'sym'=='*' */
    371     if (reg == NULL) return ERRLIB;  /* unable to load library */
    372     addtoclib(L, path, reg);
    373   }
    374   if (*sym == '*') {  /* loading only library (no function)? */
    375     lua_pushboolean(L, 1);  /* return 'true' */
    376     return 0;  /* no errors */
    377   }
    378   else {
    379     lua_CFunction f = lsys_sym(L, reg, sym);
    380     if (f == NULL)
    381       return ERRFUNC;  /* unable to find function */
    382     lua_pushcfunction(L, f);  /* else create new function */
    383     return 0;  /* no errors */
    384   }
    385 }
    386 
    387 
    388 static int ll_loadlib (lua_State *L) {
    389   const char *path = luaL_checkstring(L, 1);
    390   const char *init = luaL_checkstring(L, 2);
    391   int stat = lookforfunc(L, path, init);
    392   if (l_likely(stat == 0))  /* no errors? */
    393     return 1;  /* return the loaded function */
    394   else {  /* error; error message is on stack top */
    395     luaL_pushfail(L);
    396     lua_insert(L, -2);
    397     lua_pushstring(L, (stat == ERRLIB) ?  LIB_FAIL : "init");
    398     return 3;  /* return fail, error message, and where */
    399   }
    400 }
    401 
    402 
    403 
    404 /*
    405 ** {======================================================
    406 ** 'require' function
    407 ** =======================================================
    408 */
    409 
    410 
    411 static int readable (const char *filename) {
    412   FILE *f = fopen(filename, "r");  /* try to open file */
    413   if (f == NULL) return 0;  /* open failed */
    414   fclose(f);
    415   return 1;
    416 }
    417 
    418 
    419 /*
    420 ** Get the next name in '*path' = 'name1;name2;name3;...', changing
    421 ** the ending ';' to '\0' to create a zero-terminated string. Return
    422 ** NULL when list ends.
    423 */
    424 static const char *getnextfilename (char **path, char *end) {
    425   char *sep;
    426   char *name = *path;
    427   if (name == end)
    428     return NULL;  /* no more names */
    429   else if (*name == '\0') {  /* from previous iteration? */
    430     *name = *LUA_PATH_SEP;  /* restore separator */
    431     name++;  /* skip it */
    432   }
    433   sep = strchr(name, *LUA_PATH_SEP);  /* find next separator */
    434   if (sep == NULL)  /* separator not found? */
    435     sep = end;  /* name goes until the end */
    436   *sep = '\0';  /* finish file name */
    437   *path = sep;  /* will start next search from here */
    438   return name;
    439 }
    440 
    441 
    442 /*
    443 ** Given a path such as ";blabla.so;blublu.so", pushes the string
    444 **
    445 ** no file 'blabla.so'
    446 **	no file 'blublu.so'
    447 */
    448 static void pusherrornotfound (lua_State *L, const char *path) {
    449   luaL_Buffer b;
    450   luaL_buffinit(L, &b);
    451   luaL_addstring(&b, "no file '");
    452   luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '");
    453   luaL_addstring(&b, "'");
    454   luaL_pushresult(&b);
    455 }
    456 
    457 
    458 static const char *searchpath (lua_State *L, const char *name,
    459                                              const char *path,
    460                                              const char *sep,
    461                                              const char *dirsep) {
    462   luaL_Buffer buff;
    463   char *pathname;  /* path with name inserted */
    464   char *endpathname;  /* its end */
    465   const char *filename;
    466   /* separator is non-empty and appears in 'name'? */
    467   if (*sep != '\0' && strchr(name, *sep) != NULL)
    468     name = luaL_gsub(L, name, sep, dirsep);  /* replace it by 'dirsep' */
    469   luaL_buffinit(L, &buff);
    470   /* add path to the buffer, replacing marks ('?') with the file name */
    471   luaL_addgsub(&buff, path, LUA_PATH_MARK, name);
    472   luaL_addchar(&buff, '\0');
    473   pathname = luaL_buffaddr(&buff);  /* writable list of file names */
    474   endpathname = pathname + luaL_bufflen(&buff) - 1;
    475   while ((filename = getnextfilename(&pathname, endpathname)) != NULL) {
    476     if (readable(filename))  /* does file exist and is readable? */
    477       return lua_pushstring(L, filename);  /* save and return name */
    478   }
    479   luaL_pushresult(&buff);  /* push path to create error message */
    480   pusherrornotfound(L, lua_tostring(L, -1));  /* create error message */
    481   return NULL;  /* not found */
    482 }
    483 
    484 
    485 static int ll_searchpath (lua_State *L) {
    486   const char *f = searchpath(L, luaL_checkstring(L, 1),
    487                                 luaL_checkstring(L, 2),
    488                                 luaL_optstring(L, 3, "."),
    489                                 luaL_optstring(L, 4, LUA_DIRSEP));
    490   if (f != NULL) return 1;
    491   else {  /* error message is on top of the stack */
    492     luaL_pushfail(L);
    493     lua_insert(L, -2);
    494     return 2;  /* return fail + error message */
    495   }
    496 }
    497 
    498 
    499 static const char *findfile (lua_State *L, const char *name,
    500                                            const char *pname,
    501                                            const char *dirsep) {
    502   const char *path;
    503   lua_getfield(L, lua_upvalueindex(1), pname);
    504   path = lua_tostring(L, -1);
    505   if (l_unlikely(path == NULL))
    506     luaL_error(L, "'package.%s' must be a string", pname);
    507   return searchpath(L, name, path, ".", dirsep);
    508 }
    509 
    510 
    511 static int checkload (lua_State *L, int stat, const char *filename) {
    512   if (l_likely(stat)) {  /* module loaded successfully? */
    513     lua_pushstring(L, filename);  /* will be 2nd argument to module */
    514     return 2;  /* return open function and file name */
    515   }
    516   else
    517     return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
    518                           lua_tostring(L, 1), filename, lua_tostring(L, -1));
    519 }
    520 
    521 
    522 static int searcher_Lua (lua_State *L) {
    523   const char *filename;
    524   const char *name = luaL_checkstring(L, 1);
    525   filename = findfile(L, name, "path", LUA_LSUBSEP);
    526   if (filename == NULL) return 1;  /* module not found in this path */
    527   return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
    528 }
    529 
    530 
    531 /*
    532 ** Try to find a load function for module 'modname' at file 'filename'.
    533 ** First, change '.' to '_' in 'modname'; then, if 'modname' has
    534 ** the form X-Y (that is, it has an "ignore mark"), build a function
    535 ** name "luaopen_X" and look for it. (For compatibility, if that
    536 ** fails, it also tries "luaopen_Y".) If there is no ignore mark,
    537 ** look for a function named "luaopen_modname".
    538 */
    539 static int loadfunc (lua_State *L, const char *filename, const char *modname) {
    540   const char *openfunc;
    541   const char *mark;
    542   modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
    543   mark = strchr(modname, *LUA_IGMARK);
    544   if (mark) {
    545     int stat;
    546     openfunc = lua_pushlstring(L, modname, ct_diff2sz(mark - modname));
    547     openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
    548     stat = lookforfunc(L, filename, openfunc);
    549     if (stat != ERRFUNC) return stat;
    550     modname = mark + 1;  /* else go ahead and try old-style name */
    551   }
    552   openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
    553   return lookforfunc(L, filename, openfunc);
    554 }
    555 
    556 
    557 static int searcher_C (lua_State *L) {
    558   const char *name = luaL_checkstring(L, 1);
    559   const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP);
    560   if (filename == NULL) return 1;  /* module not found in this path */
    561   return checkload(L, (loadfunc(L, filename, name) == 0), filename);
    562 }
    563 
    564 
    565 static int searcher_Croot (lua_State *L) {
    566   const char *filename;
    567   const char *name = luaL_checkstring(L, 1);
    568   const char *p = strchr(name, '.');
    569   int stat;
    570   if (p == NULL) return 0;  /* is root */
    571   lua_pushlstring(L, name, ct_diff2sz(p - name));
    572   filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
    573   if (filename == NULL) return 1;  /* root not found */
    574   if ((stat = loadfunc(L, filename, name)) != 0) {
    575     if (stat != ERRFUNC)
    576       return checkload(L, 0, filename);  /* real error */
    577     else {  /* open function not found */
    578       lua_pushfstring(L, "no module '%s' in file '%s'", name, filename);
    579       return 1;
    580     }
    581   }
    582   lua_pushstring(L, filename);  /* will be 2nd argument to module */
    583   return 2;
    584 }
    585 
    586 
    587 static int searcher_preload (lua_State *L) {
    588   const char *name = luaL_checkstring(L, 1);
    589   lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
    590   if (lua_getfield(L, -1, name) == LUA_TNIL) {  /* not found? */
    591     lua_pushfstring(L, "no field package.preload['%s']", name);
    592     return 1;
    593   }
    594   else {
    595     lua_pushliteral(L, ":preload:");
    596     return 2;
    597   }
    598 }
    599 
    600 
    601 static void findloader (lua_State *L, const char *name) {
    602   int i;
    603   luaL_Buffer msg;  /* to build error message */
    604   /* push 'package.searchers' to index 3 in the stack */
    605   if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers")
    606                  != LUA_TTABLE))
    607     luaL_error(L, "'package.searchers' must be a table");
    608   luaL_buffinit(L, &msg);
    609   luaL_addstring(&msg, "\n\t");  /* error-message prefix for first message */
    610   /*  iterate over available searchers to find a loader */
    611   for (i = 1; ; i++) {
    612     if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) {  /* no more searchers? */
    613       lua_pop(L, 1);  /* remove nil */
    614       luaL_buffsub(&msg, 2);  /* remove last prefix */
    615       luaL_pushresult(&msg);  /* create error message */
    616       luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
    617     }
    618     lua_pushstring(L, name);
    619     lua_call(L, 1, 2);  /* call it */
    620     if (lua_isfunction(L, -2))  /* did it find a loader? */
    621       return;  /* module loader found */
    622     else if (lua_isstring(L, -2)) {  /* searcher returned error message? */
    623       lua_pop(L, 1);  /* remove extra return */
    624       luaL_addvalue(&msg);  /* concatenate error message */
    625       luaL_addstring(&msg, "\n\t");  /* prefix for next message */
    626     }
    627     else  /* no error message */
    628       lua_pop(L, 2);  /* remove both returns */
    629   }
    630 }
    631 
    632 
    633 static int ll_require (lua_State *L) {
    634   const char *name = luaL_checkstring(L, 1);
    635   lua_settop(L, 1);  /* LOADED table will be at index 2 */
    636   lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
    637   lua_getfield(L, 2, name);  /* LOADED[name] */
    638   if (lua_toboolean(L, -1))  /* is it there? */
    639     return 1;  /* package is already loaded */
    640   /* else must load package */
    641   lua_pop(L, 1);  /* remove 'getfield' result */
    642   findloader(L, name);
    643   lua_rotate(L, -2, 1);  /* function <-> loader data */
    644   lua_pushvalue(L, 1);  /* name is 1st argument to module loader */
    645   lua_pushvalue(L, -3);  /* loader data is 2nd argument */
    646   /* stack: ...; loader data; loader function; mod. name; loader data */
    647   lua_call(L, 2, 1);  /* run loader to load module */
    648   /* stack: ...; loader data; result from loader */
    649   if (!lua_isnil(L, -1))  /* non-nil return? */
    650     lua_setfield(L, 2, name);  /* LOADED[name] = returned value */
    651   else
    652     lua_pop(L, 1);  /* pop nil */
    653   if (lua_getfield(L, 2, name) == LUA_TNIL) {   /* module set no value? */
    654     lua_pushboolean(L, 1);  /* use true as result */
    655     lua_copy(L, -1, -2);  /* replace loader result */
    656     lua_setfield(L, 2, name);  /* LOADED[name] = true */
    657   }
    658   lua_rotate(L, -2, 1);  /* loader data <-> module result  */
    659   return 2;  /* return module result and loader data */
    660 }
    661 
    662 /* }====================================================== */
    663 
    664 
    665 
    666 
    667 static const luaL_Reg pk_funcs[] = {
    668   {"loadlib", ll_loadlib},
    669   {"searchpath", ll_searchpath},
    670   /* placeholders */
    671   {"preload", NULL},
    672   {"cpath", NULL},
    673   {"path", NULL},
    674   {"searchers", NULL},
    675   {"loaded", NULL},
    676   {NULL, NULL}
    677 };
    678 
    679 
    680 static const luaL_Reg ll_funcs[] = {
    681   {"require", ll_require},
    682   {NULL, NULL}
    683 };
    684 
    685 
    686 static void createsearcherstable (lua_State *L) {
    687   static const lua_CFunction searchers[] = {
    688     searcher_preload,
    689     searcher_Lua,
    690     searcher_C,
    691     searcher_Croot,
    692     NULL
    693   };
    694   int i;
    695   /* create 'searchers' table */
    696   lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
    697   /* fill it with predefined searchers */
    698   for (i=0; searchers[i] != NULL; i++) {
    699     lua_pushvalue(L, -2);  /* set 'package' as upvalue for all searchers */
    700     lua_pushcclosure(L, searchers[i], 1);
    701     lua_rawseti(L, -2, i+1);
    702   }
    703   lua_setfield(L, -2, "searchers");  /* put it in field 'searchers' */
    704 }
    705 
    706 
    707 /*
    708 ** create table CLIBS to keep track of loaded C libraries,
    709 ** setting a finalizer to close all libraries when closing state.
    710 */
    711 static void createclibstable (lua_State *L) {
    712   luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS);  /* create CLIBS table */
    713   lua_createtable(L, 0, 1);  /* create metatable for CLIBS */
    714   lua_pushcfunction(L, gctm);
    715   lua_setfield(L, -2, "__gc");  /* set finalizer for CLIBS table */
    716   lua_setmetatable(L, -2);
    717 }
    718 
    719 
    720 LUAMOD_API int luaopen_package (lua_State *L) {
    721   createclibstable(L);
    722   luaL_newlib(L, pk_funcs);  /* create 'package' table */
    723   createsearcherstable(L);
    724   /* set paths */
    725   setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT);
    726   setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
    727   /* store config information */
    728   lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
    729                      LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
    730   lua_setfield(L, -2, "config");
    731   /* set field 'loaded' */
    732   luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
    733   lua_setfield(L, -2, "loaded");
    734   /* set field 'preload' */
    735   luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
    736   lua_setfield(L, -2, "preload");
    737   lua_pushglobaltable(L);
    738   lua_pushvalue(L, -2);  /* set 'package' as upvalue for next lib */
    739   luaL_setfuncs(L, ll_funcs, 1);  /* open lib into global table */
    740   lua_pop(L, 1);  /* pop global table */
    741   return 1;  /* return 'package' table */
    742 }
    743