C++ traverses the lua table example
- 2020-04-02 02:17:29
- OfStack
C /c++ gets the table data from Lua on the stack
map<string,string> traverse_table(lua_State *L, int index)
{
map<string,string> data;
lua_pushnil(L);
//Current stack: -1 => Nil; The index => The table
index = index - 1;
while (lua_next(L, index))
{
//Current stack: -1 => The value; - 2 => The key; The index => The table
//Copy a copy of the key to the top of the stack and then do lua_tostring on it without changing the original key value
lua_pushvalue(L, -2);
//Current stack: -1 => The key; - 2 => The value; - 3 => The key; The index => The table
const char* key = lua_tostring(L, -1);
const char* value = lua_tostring(L, -2);
data[key]=value;
//Pop up the value and the copied key, leaving the original key as the next lua_next argument
lua_pop(L, 2);
//Current stack: -1 => The key; The index => The table
}
//Current stack: index => Table (by the time lua_next returns 0, it has already popped the key left over from the last time)
//So the stack is back to where it was when we entered this function
return data;
}