Consider the following lua table:
foo = {
bar1 = {a = 1, b = 2, c = "hello"},
bar2 = {a = 5, b = 2, c = "bbq"},
bar3 = {a = 76, b = 13, c = "pwnd"}
}
I am trying to iterate this table using the lua C API to retrieve the key names, bar1, bar2 and bar3. I used the lua_next(L, -2)
function to iterate as suggested by many, but the problem is that it returns the elements in random order. The order changes on each run.
I use the following code:
for( lua_pushnil(L); lua_next(L, -2) != 0; lua_pop(L, 1) )
{
printf("%s\n", lua_tostring(L, -2));
}
Most of the time, the output is unordered, such as bar2 bar1 bar3
. When lucky, it's ordered. Is there an easy way to loop the table keys in an ordered fashion? What would be the equivalent code as I use, but ordered? Thanks!
Edit:
I know I am using a map rather than an array. But in lua script we have ipairs which would work just fine for this case. I'm looking at the C API equivalent. I've found this stackoverflow answer which gives a different answer, but it doesn't work for me, so I wonder if that answer is good or relevant.