lua/c开发:lua增加自定义require方式

我们会有需要自定义加载模块逻辑的需求,比如支持从自定义格式数据包中加载一个被加密过的lua文件的方式,这在生产环境中非常常见,可以有效保护源码同时保持整洁;
lua模块管理库会从若干个loader中逐个尝试加载模块,lua原生提供了4个loader;

static const lua_CFunction searchers[] = {
    searcher_preload,
    searcher_Lua,
    searcher_C,
    searcher_Croot,
    NULL
};

需要自定义require方式,只需要替换或者增加一个新的loader即可;(了解 ll_require 函数实现)

int myloader(lua_State* L){
	// ... do something else
	luaL_loadbuffer(L, (const char*)buffer, size, fname);
	reurn 1;
}

void addloader(lua_State* L){
	lua_getfield(L, LUA_GLOBALSINDEX, "package");
	lua_getfield(L, -1, "loaders");
	lua_remove(L, -2);

	int nloader = 0;
	lua_pushnil(L);
	while (lua_next(L, -2) != 0){
		lua_pop(L, 1);
		nloader++;
	}
	lua_pushinteger(L, nloader + 1);
	lua_pushcfunction(L, nloader);
	lua_rawset(L, -3);
	lua_pop(L, 1);
}
posted @   linxx-  阅读(136)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· RFID实践——.NET IoT程序读取高频RFID卡/标签
点击右上角即可分享
微信分享提示