以下方法在lua 5.2.4版本下成功实现:
1. lua.c为所有函数的主程序,参考Makefile的编译链接 2. lua.c中 int main (int argc, char **argv) { … /* call 'pmain' in protected mode */ lua_pushcfunction(L, &pmain); … } static int pmain (lua_State *L) { ... luaL_openlibs(L); /* open libraries */ ... }
3. linit.c中 static const luaL_Reg loadedlibs[] = { {"_G", luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, {LUA_COLIBNAME, luaopen_coroutine}, {LUA_TABLIBNAME, luaopen_table}, {LUA_IOLIBNAME, luaopen_io}, {LUA_OSLIBNAME, luaopen_os}, {LUA_STRLIBNAME, luaopen_string}, {LUA_BITLIBNAME, luaopen_bit32}, {LUA_MATHLIBNAME, luaopen_math}, {LUA_DBLIBNAME, luaopen_debug},
{LUA_LOADMYLIBNAME, luaopen_mypackage},
{NULL, NULL} };
4. lualib.h中 ... #define LUA_LOADLIBNAME "package" LUAMOD_API int (luaopen_package) (lua_State *L);
#define LUA_LOADMYLIBNAME "mypackage" LUAMOD_API int (luaopen_mypackage) (lua_State *L);
/* open all previous libraries */ LUALIB_API void (luaL_openlibs) (lua_State *L); ...
5. myloadlib.c中 ... static int printhelloworld (lua_State *L) { printf("[mypackage] hello world\n"); return 0; }
static int myadd (lua_State *L) { printf("%d %d\n", (int)luaL_checknumber(L, 1), (int)luaL_checknumber(L, 2)); lua_pushnumber(L, (int)luaL_checknumber(L, 1) + (int)luaL_checknumber(L, 2)); return 1; }
static const luaL_Reg my_funcs[] = { {"printhelloworld", printhelloworld}, {"myadd", myadd}, {NULL, NULL} };
LUAMOD_API int luaopen_mypackage (lua_State *L) { /* create `package' table */ luaL_newlib(L, my_funcs);} return 1;
}
6. Makefile中 ... LIB_O= lauxlib.o lbaselib.o lbitlib.o lcorolib.o ldblib.o liolib.o \ lmathlib.o loslib.o lstrlib.o ltablib.o loadlib.o myloadlib.o linit.o ... myloadlib.o: myloadlib.c lua.h luaconf.h lauxlib.h lualib.h ...
7. lua中调用 function helloworld() mypackage.printhelloworld(); print(mypackage.myadd(11,222)); end
|
请发表评论