I am having a slight confusion of how lua_next really works. User defines a table:
a={["a1"]=20,["a2"]=30}
I want to print this table with a C++ code:
inline int lua_print(lua_State* L)
{
wxString wxReturnStr=wxEmptyString;
wxString tempString=wxEmptyString;
int nargs = lua_gettop(L);
for (int i=1; i <= nargs; i++)
{
int type = lua_type(L, i);
switch (type)
{
case LUA_TNIL:
break;
case LUA_TBOOLEAN:
tempString<<(lua_toboolean(L, i) ? "true" : "false");
break;
case LUA_TNUMBER:
tempString<<lua_tonumber(L, i);
break;
case LUA_TSTRING:
tempString<<lua_tostring(L, i);
break;
case LUA_TTABLE:
{
lua_pushnil(L);
while(lua_next(L,-2))
{
const char* key=lua_tostring(L,-2);
double val=lua_tonumber(L,-1);
lua_pop(L,1);
tempString<<key<<"="<<val<<"\t";
}
break;
}
default:
tempString<<lua_typename(L, type);
break;
}
wxReturnStr=wxReturnStr+tempString+"\n";
tempString=wxEmptyString;
}
lua_pop(L,nargs);
This code works very well when I call from Lua:
print(a) -- Works well
However, imagine I have a table in Lua as:
b={["b1"]=10, ["b2"]=15}
if I call the code as:
print(a,b) -- Twice prints only contents of b
My understanding with how lua_next work is in the following figure: [Edition #1]
Where is the bug?