###C库结构和导入到lua
导入全局性的库到lua中,这些库由C实现:
/* ** these libs are loaded by lua.c and are readily available to any Lua ** program */ static const luaL_Reg loadedlibs[] = { { "_G", luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, {LUA_COLIBNAME, luaopen_coroutine}, //.... { NULL,NULL} }; LUALIB_API void luaL_openlibs (lua_State *L) { const luaL_Reg *lib; /* "require" functions from 'loadedlibs' and set results to global table */ for (lib = loadedlibs; lib->func; lib++) { luaL_requiref(L, lib->name, lib->func, 1); lua_pop(L, 1); /* remove lib */ } }
每一个库封装了很多函数, 且每个库都由库名和open函数导入,如以协程人库为例:
{LUA_COLIBNAME, luaopen_coroutine},
通过看协程的库的创建过程可以知道如何将C函数写的库导入lua:
// 每个库必须有的open函数:luaopen_name(..) // newlib的实现就是一个table LUAMOD_API int luaopen_coroutine (lua_State *L) { luaL_newlib(L, co_funcs); return 1; } //下面是协程库的lua函数名和对应的C函数: static const luaL_Reg co_funcs[] = { { "create", luaB_cocreate}, { "resume", luaB_coresume}, { "running", luaB_corunning}, { "status", luaB_costatus}, {