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