How do I create a Lua Table in C++, and pass it to a Lua function?

核能气质少年 提交于 2019-12-17 22:53:39

问题


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?


回答1:


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..




回答2:


A couple options...

  1. Copy the map into a new Lua table, and pass the Lua table.

  2. Create a proxy table that directs reads and writes through a metatable's __index and __newindex metamethods

The drawback to (1) is all the copying, of course.

The drawback to (2) is that pairs() won't work on the proxy table

A discussion of fixes to Lua for generalized pairs is in the wiki and this mailing list thread. Generalized pairs is expected for Lua 5.2



来源:https://stackoverflow.com/questions/453769/how-do-i-create-a-lua-table-in-c-and-pass-it-to-a-lua-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!