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?
Asked
Active
Viewed 1.2k times
9

hjpotter92
- 78,589
- 36
- 144
- 183

Rocketmagnet
- 5,656
- 8
- 36
- 47
2 Answers
19
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..

Nicol Bolas
- 449,505
- 63
- 781
- 982

sean riley
- 2,633
- 1
- 22
- 22
5
A couple options...
Copy the map into a new Lua table, and pass the Lua table.
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

Doug Currie
- 40,708
- 1
- 95
- 119
-
It shouldn't be too difficult to add an iterator function to the metatable that can be used just like pairs() for tables. – David Hanak Jan 17 '09 at 18:51
-
i usually do option 2; unless the table is small and there's lots of requests to a mostly read-only table. – Javier Jan 17 '09 at 19:09