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 @ 2024-03-23 14:15  linxx-  阅读(81)  评论(0编辑  收藏  举报