So I’m reading over the c api lua docs and I notice in this code:
lua_pushnil(L); /* first key */
while (lua_next(L, t) != 0) {
/* uses 'key' (at index -2) and 'value' (at index -1) */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
and it looks normal apart from the lines where it uses -2 and -1 for the stack index
I tried changing them to positives and it didn’t seem to have any affect on the program, so why would they specifically use negatives? and why doesnt this cause a compiler error, im sure you cant use unsigned ints with negative numbers
I dont know if it makes any changes but I’m using c++ instead of c so maybe that has something to do with it
>Solution :
According to the documentation:
For convenience, most query operations in the API do not follow a strict stack discipline. Instead, they can refer to any element in the stack by using an index: A positive index represents an absolute stack position, starting at 1 as the bottom of the stack; a negative index represents an offset relative to the top of the stack. More specifically, if the stack has n elements, then index 1 represents the first element (that is, the element that was pushed onto the stack first) and index n represents the last element; index -1 also represents the last element (that is, the element at the top) and index -n represents the first element.