| 464 | |
| 465 | |
| 466 | static int ll_require (lua_State *L) { |
| 467 | const char *name = luaL_checkstring(L, 1); |
| 468 | int i; |
| 469 | lua_settop(L, 1); /* _LOADED table will be at index 2 */ |
| 470 | lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); |
| 471 | lua_getfield(L, 2, name); |
| 472 | if (lua_toboolean(L, -1)) { /* is it there? */ |
| 473 | if (lua_touserdata(L, -1) == sentinel) /* check loops */ |
| 474 | luaL_error(L, "loop or previous error loading module " LUA_QS, name); |
| 475 | return 1; /* package is already loaded */ |
| 476 | } |
| 477 | /* else must load it; iterate over available loaders */ |
| 478 | lua_getfield(L, LUA_ENVIRONINDEX, "loaders"); |
| 479 | if (!lua_istable(L, -1)) |
| 480 | luaL_error(L, LUA_QL("package.loaders") " must be a table"); |
| 481 | lua_pushliteral(L, ""); /* error message accumulator */ |
| 482 | for (i=1; ; i++) { |
| 483 | lua_rawgeti(L, -2, i); /* get a loader */ |
| 484 | if (lua_isnil(L, -1)) |
| 485 | luaL_error(L, "module " LUA_QS " not found:%s", |
| 486 | name, lua_tostring(L, -2)); |
| 487 | lua_pushstring(L, name); |
| 488 | lua_call(L, 1, 1); /* call it */ |
| 489 | if (lua_isfunction(L, -1)) /* did it find module? */ |
| 490 | break; /* module loaded successfully */ |
| 491 | else if (lua_isstring(L, -1)) /* loader returned error message? */ |
| 492 | lua_concat(L, 2); /* accumulate it */ |
| 493 | else |
| 494 | lua_pop(L, 1); |
| 495 | } |
| 496 | lua_pushlightuserdata(L, sentinel); |
| 497 | lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */ |
| 498 | lua_pushstring(L, name); /* pass name as argument to module */ |
| 499 | lua_call(L, 1, 1); /* run loaded module */ |
| 500 | if (!lua_isnil(L, -1)) /* non-nil return? */ |
| 501 | lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ |
| 502 | lua_getfield(L, 2, name); |
| 503 | if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */ |
| 504 | lua_pushboolean(L, 1); /* use true as result */ |
| 505 | lua_pushvalue(L, -1); /* extra copy to be returned */ |
| 506 | lua_setfield(L, 2, name); /* _LOADED[name] = true */ |
| 507 | } |
| 508 | return 1; |
| 509 | } |
| 510 | |
| 511 | /* }====================================================== */ |
| 512 |
nothing calls this directly
no test coverage detected