lua State加载部分库

lua State加载部分库

 

   在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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值