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

时间:2016-08-26 16:44:00

标签: c++ dictionary lua

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

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

这是地图。

    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;
}

1 个答案:

答案 0 :(得分:0)

我不能推荐Sol2(https://github.com/ThePhD/sol2)足够C ++ / Lua。

在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