如何在 C++ 中创建 Lua 表,并将其传递给 Lua 函数?

2021-12-30 00:00:00 string lua c++ map lua-table

在 C++ 中,我有一个 map,其中包含未知数量的条目.如何将其传递给 Lua 函数,以便 Lua 函数可以将数据用作表?

In C++, I have a map<string, string>, containing an unknown number of entries. How can I pass this to a Lua function, so that the Lua function can use the data as a table?

推荐答案

如果你想要一个真正的lua表:

if you want a real lua table:

lua_newtable(L);
int top = lua_gettop(L);

for (std::map::iterator it = mymap.begin(); it != mymap.end(); ++it) {
    const char* key = it->first.c_str();
    const char* value = it->second.c_str();
    lua_pushlstring(L, key, it->first.size());
    lua_pushlstring(L, value, it->second.size());
    lua_settable(L, top);
}

用正确的地图类型替换...

with the right types for your map substituted in..

相关文章