Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua C API: what's the difference between lua_gettop() and -1?

Tags:

c++

c

lua

I don't really understand stack exactly.

lua_gettop()

Returns the index of the top element in the stack. Because indices start at 1, this result is equal to the number of elements in the stack (and so 0 means an empty stack).

so what's the difference between it and -1?

lua_getglobal(L,"Foo");
if( lua_isfunction(L,lua_gettop(L)) ) {

lua_getglobal(L,"Foo");
if( lua_isfunction(L,-1) ) {
like image 411
deepspace Avatar asked Aug 26 '13 13:08

deepspace


2 Answers

You can imagine the stack as growing from the bottom, with the bottom (i.e., the first pushed) element having index 1, then you push another element (index 2), then another one (index 3), etc.. So you have this situation:

+-----------------------+
| element with index 6  | <-- top ("relative" index -1)
+-----------------------+
| element with index 5  | <-- -2
+-----------------------+
| element with index 4  | <-- -3
+-----------------------+
| element with index 3  | <-- -4
+-----------------------+
| element with index 2  | <-- -5
+-----------------------+
| element with index 1  | <-- bottom ("relative" index -6 )
+-----------------------+

You could also say that the "normal index" (the one indexing from the bottom) is the absolute index of the element (like that of an array in C, besides starting from 1). Instead the negative index is "relative" to the top of stack.lua_gettop gives you the absolute index of the stack top (which has always relative index -1).

Why are there two ways of indexing the stack, then? Because sometimes it is useful to access the elements like an array (using an absolute index) and sometimes you only need to access the last pushed elements (so indexing from the top).

BTW, I usually visualize the Lua stack reversed: starting from above and growing downwards (i.e. the stack top is at the bottom of my mental representation). I find this mental model more useful because I interpret the index -1 as "step back in code (upwards, therefore) until you find the the first push". In this fashion, index -2 would be "step back in code until you find the second push", etc.. All this helps me quickly identify where I pushed what.

However, to avoid confusion, here I used a more classical representation, where the stack top is drawn really at the top!

like image 91
Lorenzo Donati -- Codidact.com Avatar answered Nov 11 '22 07:11

Lorenzo Donati -- Codidact.com


From PIL (http://www.lua.org/pil/24.2.3.html)

Notice that a negative index -x is equivalent to the positive index gettop - x + 1.

Therefore

if( lua_isfunction(L,lua_gettop(L)) ) {

does the same than

if( lua_isfunction(L,-1) ) {
like image 43
jcm Avatar answered Nov 11 '22 08:11

jcm