我不是很了解堆栈。
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).
那么它和-1有什么区别呢?
lua_getglobal(L,"Foo");
if( lua_isfunction(L,lua_gettop(L)) ) {
lua_getglobal(L,"Foo");
if( lua_isfunction(L,-1) ) {
最佳答案
你可以想象堆栈从底部开始增长,底部(即第一个被插入的)元素的索引为 1,然后你插入另一个元素(索引 2),然后是另一个元素(索引 3),等等。所以你有这种情况:
+-----------------------+
| 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 )
+-----------------------+
您也可以说“普通索引”(从底部开始索引)是元素的绝对索引(类似于 C 中的数组,除了从 1 开始)。相反,负索引是“相对于”堆栈顶部的。lua_gettop
为您提供堆栈顶部的绝对索引(它始终具有相对索引 -1
)。
那么为什么有两种索引堆栈的方法呢?因为有时像数组一样访问元素(使用绝对索引)很有用,而有时您只需要访问最后推送的元素(因此从顶部开始索引)。
顺便说一句,我通常将 Lua 堆栈形象化为颠倒的:从上开始向下增长(即堆栈顶部在我心理表征的底部)。我发现这种心智模型更有用,因为我将索引 -1 解释为“退回代码(因此向上)直到找到第一个推送”。以这种方式,索引 -2 将是“退回代码,直到找到第二个推送”,等等。所有这些都有助于我快速确定我推送了什么内容。
但是,为了避免混淆,我在这里使用了更经典的表示方式,其中堆栈顶部确实绘制在顶部!
关于c++ - Lua C API : what's the difference between lua_gettop() and -1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18445022/