代码改变世界

lua State加载部分库

  youxin  阅读(836)  评论(0编辑  收藏  举报

    在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
 
 }
 
复制代码

 

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2014-10-28 python操作json
2014-10-28 jQuery deferred when用法
2014-10-28 tcp 服务端如何判断客户端断开连接
2013-10-28 css 优先级
2012-10-28 js The Yellow Fade Technique
2012-10-28 javascript中的toString()方法
2011-10-28 乔布斯的10个与众不同:践行另类思考
点击右上角即可分享
微信分享提示