我希望能够使用 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/