LuaL openlib
lastmod 2026-11-10created 2019-05-025 edits
luaL_openlib은 Lua 5.0 과 5.1 의 보조 라이브러리 함수로 luaL_Reg 배열에 담긴 C 함수들을 지정한 이름의 라이브러리 테이블에 등록한다. libname 이 있으면 전역 테이블과 _LOADED 에서 그 이름의 테이블을 찾거나 새로 만든 뒤 함수를 채우고 nup 개의 업밸류를 각 함수에 공유시킨다. 5.1 에서 luaL_register 로 대체되었고 5.2 이후 제거되었으나 LuaJIT 에는 남아 있다.
Code
void luaL_openlib(lua_State * L, char const * libname, luaL_Reg const * l, int nup)
{
lj_lib_checkfpu(L);
if (libname) {
int size = libsize(l);
/* check whether lib already exists */
luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 16);
lua_getfield(L, -1, libname); /* get _LOADED[libname] */
if (!lua_istable(L, -1)) { /* not found? */
lua_pop(L, 1); /* remove previous result */
/* try global variable (and create one if it does not exist) */
if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
lj_err_callerv(L, LJ_ERR_BADMODN, libname);
lua_pushvalue(L, -1);
lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
}
lua_remove(L, -2); /* remove _LOADED table */
lua_insert(L, -(nup+1)); /* move library table to below upvalues */
}
for (; l->name; l++) {
int i;
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -nup);
lua_pushcclosure(L, l->func, nup);
lua_setfield(L, -(nup+2), l->name);
}
lua_pop(L, nup); /* remove upvalues */
}