• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

luaState加载部分库

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

   在lua中,通常我们用luaL_openlibs(L)加载所有的lub标准库,但是有时候我们想只加载部分,有没有什么好的办法呢?在luaproc看到如下办法:

static void registerlib( lua_State *L, const char *name, lua_CFunction f ) {
    lua_getglobal( L, "package" );
    lua_getfield( L, -1, "preload" );
    lua_pushcfunction( L, f );
    lua_setfield( L, -2, name );
    lua_pop( L, 2 );
}

static void openlibs( lua_State *L ) {
    lua_cpcall( L, luaopen_base, NULL );
    lua_cpcall( L, luaopen_package, NULL );
    registerlib( L, "io", luaopen_io );
    registerlib( L, "os", luaopen_os );
    registerlib( L, "table", luaopen_table );
    registerlib( L, "string", luaopen_string );
    registerlib( L, "math", luaopen_math );
    registerlib( L, "debug", luaopen_debug );
}
int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);

Calls the C function func in protected mode. func starts with only one element in its stack, a light userdata containing ud. In case of errors, lua_cpcall returns the same error codes as lua_pcall, plus the error object on the top of the stack; otherwise, it returns zero, and does not change the stack. All values returned by func are discarded.

上面是5.1的做法。luaproc新做法如下:

 static void luaproc_reglualib( lua_State *L, const char *name,
                                lua_CFunction f ) {
   lua_getglobal( L, "package" );
   lua_getfield( L, -1, "preload" );
   lua_pushcfunction( L, f );
   lua_setfield( L, -2, name );
   lua_pop( L, 2 );
 }
 
 static void luaproc_openlualibs( lua_State *L ) {
   requiref( L, "_G", luaopen_base, FALSE );
   requiref( L, "package", luaopen_package, TRUE );
   luaproc_reglualib( L, "io", luaopen_io );
   luaproc_reglualib( L, "os", luaopen_os );
   luaproc_reglualib( L, "table", luaopen_table );
   luaproc_reglualib( L, "string", luaopen_string );
   luaproc_reglualib( L, "math", luaopen_math );
   luaproc_reglualib( L, "debug", luaopen_debug );
 #if (LUA_VERSION_NUM == 502)
   luaproc_reglualib( L, "bit32", luaopen_bit32 );
 #endif
 #if (LUA_VERSION_NUM >= 502)
   luaproc_reglualib( L, "coroutine", luaopen_coroutine );
 #endif
 #if (LUA_VERSION_NUM >= 503)
   luaproc_reglualib( L, "utf8", luaopen_utf8 );
 #endif
 
 }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
lua table操作实例详解 lua_gettable发布时间:2022-07-22
下一篇:
Step By Step(Lua-C API简介)发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap