c++clua-apilua-c++-connection

Why is this program using negative ints specifically?


I'm reading over the C API Lua documentation, 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);
}

It looks normal, apart from the lines where it uses -2 and -1 for the stack indexes.

I tried changing them to positives, and it didn't seem to have any affect on the program. Why would they specifically use negatives? Why doesn't this cause a compiler error? I'm sure you can't use unsigned ints with negative numbers.

I don’t 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.