代码之家  ›  专栏  ›  技术社区  ›  Zack Lee

如何用C++检查预加载模块在Lua中的存在

  •  1
  • Zack Lee  · 技术社区  · 6 年前

    我想知道如何检查是否有一个预装模块存在或不在Lua使用C++。

    我的代码:

    #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() 函数以便我的代码可以按预期工作?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Henri Menke    6 年前

    检查一下这个区域 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;
    }