c++ - Lua C API: what's the difference between lua_gettop() and -1? -
i don't understand stack exactly.
lua_gettop()
returns index of top element in stack. because indices start @ 1, result equal number of elements in stack (and 0 means empty stack).
so what's difference between , -1?
lua_getglobal(l,"foo"); if( lua_isfunction(l,lua_gettop(l)) ) { lua_getglobal(l,"foo"); if( lua_isfunction(l,-1) ) {
you can imagine stack growing bottom, bottom (i.e., first pushed) element having index 1, push element (index 2), 1 (index 3), etc.. have situation:
+-----------------------+ | element index 6 | <-- top ("relative" index -1) +-----------------------+ | element index 5 | <-- -2 +-----------------------+ | element index 4 | <-- -3 +-----------------------+ | element index 3 | <-- -4 +-----------------------+ | element index 2 | <-- -5 +-----------------------+ | element index 1 | <-- bottom ("relative" index -6 ) +-----------------------+
you "normal index" (the 1 indexing bottom) absolute index of element (like of array in c, besides starting 1). instead negative index "relative" top of stack.lua_gettop
gives absolute index of stack top (which has relative index -1
).
why there 2 ways of indexing stack, then? because useful access elements array (using absolute index) , need access last pushed elements (so indexing top).
btw, visualize lua stack reversed: starting above , growing downwards (i.e. stack top @ bottom of mental representation). find mental model more useful because interpret index -1 "step in code (upwards, therefore) until find the first push". in fashion, index -2 "step in code until find second push", etc.. helps me identify pushed what.
however, avoid confusion, here used more classical representation, stack top drawn @ top!
Comments
Post a Comment