c++ - 返回 C++ 中的映射以用作 lua 中的表

标签 c++ dictionary lua

我希望能够使用 C++ 在 lua 中返回一个值表,而不是用户数据、映射中存储的数据,如整数、字符串等。我该怎么做呢?

抱歉,我没有完整的示例。

这是 map 。

    std::map<uint16_t, std::map<std::string, uint32_t>> myMap;

    void getMyMap(uint16_t i, std::string a, uint32_t& v) {
        v = myMap[i][a];
    }

我知道这不是模板,但假设它是。

编辑:

我自己想出来的。我不会确切地告诉你我在做什么,但我会使用上面的代码提供一个通用的详细答案。

std::map<uint16_t, std::map<std::string, uint32_t>> myMap;

void getMyMap(uint16_t i, std::string a, uint32_t& v) {
    v = myMap[i][a];
}

std::map<std::string, size_t> getMapData(uint16_t i){
    return myMap[i];
}


int LuaReturnTableOfMap(lua_State *L)
{
    uint16_t data = 2;// used just for this example
    // get the data stored
    std::map<std::string, size_t> m = getMapData(data);
    // get the size of the map
    size_t x = m.size();

    // create the table which we will be returning with x amount of elements
    lua_createtable(L, 0, x);

    // populate the table with values which we want to return
    for(auto const &it : m){
        std::string str = it.first;
        const char* field = str.c_str();
        lua_pushnumber(L, it.second);
        lua_setField(L, -2, field);
    }
    // tell lua we are returning 1 value (which is the table)
    return 1;
}

最佳答案

对于 C++/Lua,我极力推荐 Sol2 ( https://github.com/ThePhD/sol2)。

在 c++ 中,您可以分配嵌套映射,它足够智能,可以为您创建嵌套的 lua 表:

std::map<int, std::map<std::string, int>> nestedmap;
std::map<std::string, int> innermap;
innermap["frank"] = 15;
nestedmap[2] = innermap;

sol::state lua;
lua.set("mymap", nestedmap);

然后在你的lua脚本中,你可以像访问一个表一样访问它:

print("Testing nested map: " .. mymap[2]["frank"]) -- prints 15

关于c++ - 返回 C++ 中的映射以用作 lua 中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39171060/

相关文章:

lua - NeoVim - 检查 Lua 中是否存在 Vim 函数

c++ - 使用 LuaBind 将 C++ 类导出到 Lua 时发生访问冲突

c++ - 使用 MINGW 并链接 CPLEX 库从 Linux 编译 Windows 可执行文件

C++ 格式化程序取消拆分行

java - 从 TreeMap 中检索最后 n 个值

c# - WPF 绑定(bind)到带有类的字典

algorithm - 检查十六进制是否在具有加权六角形的六角形平铺范围内

C++ char * const vs char *,为什么有时一个有时另一个

c++ - 使用可变数量的 std::thread 的引用问题

c++ - 在没有 c++11 的情况下删除 map 最后插入的元素的正确方法是什么?