Lua C++ Table Iteration -
i having slight confusion of how lua_next works. user defines table:
a={["a1"]=20,["a2"]=30}
i want print table c++ code:
inline int lua_print(lua_state* l) { wxstring wxreturnstr=wxemptystring; wxstring tempstring=wxemptystring; int nargs = lua_gettop(l); (int i=1; <= 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 when call lua:
print(a) -- works
however, imagine have table in lua as:
b={["b1"]=10, ["b2"]=15}
if call code as:
print(a,b) -- twice prints contents of b
my understanding how lua_next work in following figure: [edition #1]
where bug?
the bug in lua_next(l, -2)
line, because -2 refers stack top minus one, happens here last argument print
.
use lua_next(l, i)
instead.
upd: lua stack indexes subject float when moving code around @ development stage, general advice pin indexes sml int t = lua_gettop(l)
after getting/pushing/considering values , use t
instead of -n
(though specific case appears sort of keystroke bug.)
Comments
Post a Comment