Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/lua/blob/master/loadlib.c # lua [Ported from github.com/lua/lua] Cast in 'rl_readline_name' Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `lua / loadlib.c` 748 lines ยท 22899 bytes Raw Blame History 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 18 #include 19 #include 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 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 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 ** External strings created by DLLs may need the DLL code to be 311 ** deallocated. This implies that a DLL can only be unloaded after all 312 ** its strings were deallocated. To ensure that, we create a 'library 313 ** string' to represent each DLL, and when this string is deallocated 314 ** it closes its corresponding DLL. 315 ** (The string itself is irrelevant; its userdata is the DLL pointer.) 316 */ 317 318 319 /* 320 ** return registry.CLIBS[path] 321 */ 322 static void *checkclib (lua_State *L, const char *path) { 323 void *plib; 324 lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); 325 lua_getfield(L, -1, path); 326 plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ 327 lua_pop(L, 2); /* pop CLIBS table and 'plib' */ 328 return plib; 329 } 330 331 332 /* 333 ** Deallocate function for library strings. 334 ** Unload the DLL associated with the string being deallocated. 335 */ 336 static void *freelib (void *ud, void *ptr, size_t osize, size_t nsize) { 337 /* string itself is irrelevant and static */ 338 (void)ptr; (void)osize; (void)nsize; 339 lsys_unloadlib(ud); /* unload library represented by the string */ 340 return NULL; 341 } 342 343 344 /* 345 ** Create a library string that, when deallocated, will unload 'plib' 346 */ 347 static void createlibstr (lua_State *L, void *plib) { 348 /* common content for all library strings */ 349 static const char dummy[] = "`01234567890`"; 350 lua_pushexternalstring(L, dummy, sizeof(dummy) - 1, freelib, plib); 351 } 352 353 354 /* 355 ** registry.CLIBS[path] = plib -- for queries. 356 ** Also create a reference to strlib, so that the library string will 357 ** only be collected when registry.CLIBS is collected. 358 */ 359 static void addtoclib (lua_State *L, const char *path, void *plib) { 360 lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); 361 lua_pushlightuserdata(L, plib); 362 lua_setfield(L, -2, path); /* CLIBS[path] = plib */ 363 createlibstr(L, plib); 364 luaL_ref(L, -2); /* keep library string in CLIBS */ 365 lua_pop(L, 1); /* pop CLIBS table */ 366 } 367 368 369 /* error codes for 'lookforfunc' */ 370 #define ERRLIB 1 371 #define ERRFUNC 2 372 373 /* 374 ** Look for a C function named 'sym' in a dynamically loaded library 375 ** 'path'. 376 ** First, check whether the library is already loaded; if not, try 377 ** to load it. 378 ** Then, if 'sym' is '*', return true (as library has been loaded). 379 ** Otherwise, look for symbol 'sym' in the library and push a 380 ** C function with that symbol. 381 ** Return 0 with 'true' or a function in the stack; in case of 382 ** errors, return an error code with an error message in the stack. 383 */ 384 static int lookforfunc (lua_State *L, const char *path, const char *sym) { 385 void *reg = checkclib(L, path); /* check loaded C libraries */ 386 if (reg == NULL) { /* must load library? */ 387 reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */ 388 if (reg == NULL) return ERRLIB; /* unable to load library */ 389 addtoclib(L, path, reg); 390 } 391 if (*sym == '*') { /* loading only library (no function)? */ 392 lua_pushboolean(L, 1); /* return 'true' */ 393 return 0; /* no errors */ 394 } 395 else { 396 lua_CFunction f = lsys_sym(L, reg, sym); 397 if (f == NULL) 398 return ERRFUNC; /* unable to find function */ 399 lua_pushcfunction(L, f); /* else create new function */ 400 return 0; /* no errors */ 401 } 402 } 403 404 405 static int ll_loadlib (lua_State *L) { 406 const char *path = luaL_checkstring(L, 1); 407 const char *init = luaL_checkstring(L, 2); 408 int stat = lookforfunc(L, path, init); 409 if (l_likely(stat == 0)) /* no errors? */ 410 return 1; /* return the loaded function */ 411 else { /* error; error message is on stack top */ 412 luaL_pushfail(L); 413 lua_insert(L, -2); 414 lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); 415 return 3; /* return fail, error message, and where */ 416 } 417 } 418 419 420 421 /* 422 ** {====================================================== 423 ** 'require' function 424 ** ======================================================= 425 */ 426 427 428 static int readable (const char *filename) { 429 FILE *f = fopen(filename, "r"); /* try to open file */ 430 if (f == NULL) return 0; /* open failed */ 431 fclose(f); 432 return 1; 433 } 434 435 436 /* 437 ** Get the next name in '*path' = 'name1;name2;name3;...', changing 438 ** the ending ';' to '\0' to create a zero-terminated string. Return 439 ** NULL when list ends. 440 */ 441 static const char *getnextfilename (char **path, char *end) { 442 char *sep; 443 char *name = *path; 444 if (name == end) 445 return NULL; /* no more names */ 446 else if (*name == '\0') { /* from previous iteration? */ 447 *name = *LUA_PATH_SEP; /* restore separator */ 448 name++; /* skip it */ 449 } 450 sep = strchr(name, *LUA_PATH_SEP); /* find next separator */ 451 if (sep == NULL) /* separator not found? */ 452 sep = end; /* name goes until the end */ 453 *sep = '\0'; /* finish file name */ 454 *path = sep; /* will start next search from here */ 455 return name; 456 } 457 458 459 /* 460 ** Given a path such as ";blabla.so;blublu.so", pushes the string 461 ** 462 ** no file 'blabla.so' 463 ** no file 'blublu.so' 464 */ 465 static void pusherrornotfound (lua_State *L, const char *path) { 466 luaL_Buffer b; 467 luaL_buffinit(L, &b); 468 luaL_addstring(&b, "no file '"); 469 luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '"); 470 luaL_addstring(&b, "'"); 471 luaL_pushresult(&b); 472 } 473 474 475 static const char *searchpath (lua_State *L, const char *name, 476 const char *path, 477 const char *sep, 478 const char *dirsep) { 479 luaL_Buffer buff; 480 char *pathname; /* path with name inserted */ 481 char *endpathname; /* its end */ 482 const char *filename; 483 /* separator is non-empty and appears in 'name'? */ 484 if (*sep != '\0' && strchr(name, *sep) != NULL) 485 name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ 486 luaL_buffinit(L, &buff); 487 /* add path to the buffer, replacing marks ('?') with the file name */ 488 luaL_addgsub(&buff, path, LUA_PATH_MARK, name); 489 luaL_addchar(&buff, '\0'); 490 pathname = luaL_buffaddr(&buff); /* writable list of file names */ 491 endpathname = pathname + luaL_bufflen(&buff) - 1; 492 while ((filename = getnextfilename(&pathname, endpathname)) != NULL) { 493 if (readable(filename)) /* does file exist and is readable? */ 494 return lua_pushstring(L, filename); /* save and return name */ 495 } 496 luaL_pushresult(&buff); /* push path to create error message */ 497 pusherrornotfound(L, lua_tostring(L, -1)); /* create error message */ 498 return NULL; /* not found */ 499 } 500 501 502 static int ll_searchpath (lua_State *L) { 503 const char *f = searchpath(L, luaL_checkstring(L, 1), 504 luaL_checkstring(L, 2), 505 luaL_optstring(L, 3, "."), 506 luaL_optstring(L, 4, LUA_DIRSEP)); 507 if (f != NULL) return 1; 508 else { /* error message is on top of the stack */ 509 luaL_pushfail(L); 510 lua_insert(L, -2); 511 return 2; /* return fail + error message */ 512 } 513 } 514 515 516 static const char *findfile (lua_State *L, const char *name, 517 const char *pname, 518 const char *dirsep) { 519 const char *path; 520 lua_getfield(L, lua_upvalueindex(1), pname); 521 path = lua_tostring(L, -1); 522 if (l_unlikely(path == NULL)) 523 luaL_error(L, "'package.%s' must be a string", pname); 524 return searchpath(L, name, path, ".", dirsep); 525 } 526 527 528 static int checkload (lua_State *L, int stat, const char *filename) { 529 if (l_likely(stat)) { /* module loaded successfully? */ 530 lua_pushstring(L, filename); /* will be 2nd argument to module */ 531 return 2; /* return open function and file name */ 532 } 533 else 534 return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s", 535 lua_tostring(L, 1), filename, lua_tostring(L, -1)); 536 } 537 538 539 static int searcher_Lua (lua_State *L) { 540 const char *filename; 541 const char *name = luaL_checkstring(L, 1); 542 filename = findfile(L, name, "path", LUA_LSUBSEP); 543 if (filename == NULL) return 1; /* module not found in this path */ 544 return checkload(L, (luaL_loadfilex(L, filename, "bt") == LUA_OK), filename); 545 } 546 547 548 /* 549 ** Try to find a load function for module 'modname' at file 'filename'. 550 ** First, change '.' to '_' in 'modname'; then, if 'modname' has 551 ** the form X-Y (that is, it has an "ignore mark"), build a function 552 ** name "luaopen_X" and look for it. (For compatibility, if that 553 ** fails, it also tries "luaopen_Y".) If there is no ignore mark, 554 ** look for a function named "luaopen_modname". 555 */ 556 static int loadfunc (lua_State *L, const char *filename, const char *modname) { 557 const char *openfunc; 558 const char *mark; 559 modname = luaL_gsub(L, modname, ".", LUA_OFSEP); 560 mark = strchr(modname, *LUA_IGMARK); 561 if (mark) { 562 int stat; 563 openfunc = lua_pushlstring(L, modname, ct_diff2sz(mark - modname)); 564 openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc); 565 stat = lookforfunc(L, filename, openfunc); 566 if (stat != ERRFUNC) return stat; 567 modname = mark + 1; /* else go ahead and try old-style name */ 568 } 569 openfunc = lua_pushfstring(L, LUA_POF"%s", modname); 570 return lookforfunc(L, filename, openfunc); 571 } 572 573 574 static int searcher_C (lua_State *L) { 575 const char *name = luaL_checkstring(L, 1); 576 const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); 577 if (filename == NULL) return 1; /* module not found in this path */ 578 return checkload(L, (loadfunc(L, filename, name) == 0), filename); 579 } 580 581 582 static int searcher_Croot (lua_State *L) { 583 const char *filename; 584 const char *name = luaL_checkstring(L, 1); 585 const char *p = strchr(name, '.'); 586 int stat; 587 if (p == NULL) return 0; /* is root */ 588 lua_pushlstring(L, name, ct_diff2sz(p - name)); 589 filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); 590 if (filename == NULL) return 1; /* root not found */ 591 if ((stat = loadfunc(L, filename, name)) != 0) { 592 if (stat != ERRFUNC) 593 return checkload(L, 0, filename); /* real error */ 594 else { /* open function not found */ 595 lua_pushfstring(L, "no module '%s' in file '%s'", name, filename); 596 return 1; 597 } 598 } 599 lua_pushstring(L, filename); /* will be 2nd argument to module */ 600 return 2; 601 } 602 603 604 static int searcher_preload (lua_State *L) { 605 const char *name = luaL_checkstring(L, 1); 606 lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); 607 if (lua_getfield(L, -1, name) == LUA_TNIL) { /* not found? */ 608 lua_pushfstring(L, "no field package.preload['%s']", name); 609 return 1; 610 } 611 else { 612 lua_pushliteral(L, ":preload:"); 613 return 2; 614 } 615 } 616 617 618 static void findloader (lua_State *L, const char *name) { 619 int i; 620 luaL_Buffer msg; /* to build error message */ 621 /* push 'package.searchers' to index 3 in the stack */ 622 if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers") 623 != LUA_TTABLE)) 624 luaL_error(L, "'package.searchers' must be a table"); 625 luaL_buffinit(L, &msg); 626 luaL_addstring(&msg, "\n\t"); /* error-message prefix for first message */ 627 /* iterate over available searchers to find a loader */ 628 for (i = 1; ; i++) { 629 if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) { /* no more searchers? */ 630 lua_pop(L, 1); /* remove nil */ 631 luaL_buffsub(&msg, 2); /* remove last prefix */ 632 luaL_pushresult(&msg); /* create error message */ 633 luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1)); 634 } 635 lua_pushstring(L, name); 636 lua_call(L, 1, 2); /* call it */ 637 if (lua_isfunction(L, -2)) /* did it find a loader? */ 638 return; /* module loader found */ 639 else if (lua_isstring(L, -2)) { /* searcher returned error message? */ 640 lua_pop(L, 1); /* remove extra return */ 641 luaL_addvalue(&msg); /* concatenate error message */ 642 luaL_addstring(&msg, "\n\t"); /* prefix for next message */ 643 } 644 else /* no error message */ 645 lua_pop(L, 2); /* remove both returns */ 646 } 647 } 648 649 650 static int ll_require (lua_State *L) { 651 const char *name = luaL_checkstring(L, 1); 652 lua_settop(L, 1); /* LOADED table will be at index 2 */ 653 lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); 654 lua_getfield(L, 2, name); /* LOADED[name] */ 655 if (lua_toboolean(L, -1)) /* is it there? */ 656 return 1; /* package is already loaded */ 657 /* else must load package */ 658 lua_pop(L, 1); /* remove 'getfield' result */ 659 findloader(L, name); 660 lua_rotate(L, -2, 1); /* function <-> loader data */ 661 lua_pushvalue(L, 1); /* name is 1st argument to module loader */ 662 lua_pushvalue(L, -3); /* loader data is 2nd argument */ 663 /* stack: ...; loader data; loader function; mod. name; loader data */ 664 lua_call(L, 2, 1); /* run loader to load module */ 665 /* stack: ...; loader data; result from loader */ 666 if (!lua_isnil(L, -1)) /* non-nil return? */ 667 lua_setfield(L, 2, name); /* LOADED[name] = returned value */ 668 else 669 lua_pop(L, 1); /* pop nil */ 670 if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */ 671 lua_pushboolean(L, 1); /* use true as result */ 672 lua_copy(L, -1, -2); /* replace loader result */ 673 lua_setfield(L, 2, name); /* LOADED[name] = true */ 674 } 675 lua_rotate(L, -2, 1); /* loader data <-> module result */ 676 return 2; /* return module result and loader data */ 677 } 678 679 /* }====================================================== */ 680 681 682 683 684 static const luaL_Reg pk_funcs[] = { 685 {"loadlib", ll_loadlib}, 686 {"searchpath", ll_searchpath}, 687 /* placeholders */ 688 {"preload", NULL}, 689 {"cpath", NULL}, 690 {"path", NULL}, 691 {"searchers", NULL}, 692 {"loaded", NULL}, 693 {NULL, NULL} 694 }; 695 696 697 static const luaL_Reg ll_funcs[] = { 698 {"require", ll_require}, 699 {NULL, NULL} 700 }; 701 702 703 static void createsearcherstable (lua_State *L) { 704 static const lua_CFunction searchers[] = { 705 searcher_preload, 706 searcher_Lua, 707 searcher_C, 708 searcher_Croot, 709 NULL 710 }; 711 int i; 712 /* create 'searchers' table */ 713 lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); 714 /* fill it with predefined searchers */ 715 for (i=0; searchers[i] != NULL; i++) { 716 lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ 717 lua_pushcclosure(L, searchers[i], 1); 718 lua_rawseti(L, -2, i+1); 719 } 720 lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ 721 } 722 723 724 LUAMOD_API int luaopen_package (lua_State *L) { 725 luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */ 726 lua_pop(L, 1); /* will not use it now */ 727 luaL_newlib(L, pk_funcs); /* create 'package' table */ 728 createsearcherstable(L); 729 /* set paths */ 730 setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); 731 setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); 732 /* store config information */ 733 lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" 734 LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); 735 lua_setfield(L, -2, "config"); 736 /* set field 'loaded' */ 737 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); 738 lua_setfield(L, -2, "loaded"); 739 /* set field 'preload' */ 740 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); 741 lua_setfield(L, -2, "preload"); 742 lua_pushglobaltable(L); 743 lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ 744 luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ 745 lua_pop(L, 1); /* pop global table */ 746 return 1; /* return 'package' table */ 747 } 748