我想知道如何使用C ++检查Lua中是否存在预加载的模块。
我的代码:
#include "lua.hpp"
bool isModuleAvailable(lua_State *L, std::string name)
{
//what should be here?
return false;
}
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_settop(L, 0);
luaL_dostring(L, "package.preload['A'] = function()\n"
"local a = {}\n"
"return a\n"
"end\n");
luaL_dostring(L, "package.preload['B'] = function()\n"
"local b = {}\n"
"return b\n"
"end\n");
if (isModuleAvailable(L, "A"))
std::cout << "Module Available" << '\n';
else
std::cout << "Module Not Available" << '\n';
if (isModuleAvailable(L, "B"))
std::cout << "Module Available" << '\n';
else
std::cout << "Module Not Available" << '\n';
if (isModuleAvailable(L, "C"))
std::cout << "Module Available" << '\n';
else
std::cout << "Module Not Available" << '\n';
lua_close(L);
}
我得到的结果:
Module Not Available
Module Not Available
Module Not Available
我想要的结果:
Module Available
Module Available
Module Not Available
如何创建isModuleAvailable()
函数,以便我的代码可以按预期工作?
答案 0 :(得分:3)
只需检查字段package.preload[name]
是否为nil
。我还将该函数重命名为isModulePreloaded
,因为这就是检查。
bool isModulePreloaded(lua_State *L, std::string const &name) {
lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
lua_getfield(L, -1, name.c_str());
bool is_preloaded = !lua_isnil(L, -1);
lua_pop(L, 3);
return is_preloaded;
}