我并不完全理解堆栈.
lua_gettop()
Run Code Online (Sandbox Code Playgroud)
返回堆栈中顶部元素的索引.因为索引从1开始,所以此结果等于堆栈中元素的数量(因此0表示空堆栈).
那么它与-1之间有什么区别?
lua_getglobal(L,"Foo");
if( lua_isfunction(L,lua_gettop(L)) ) {
lua_getglobal(L,"Foo");
if( lua_isfunction(L,-1) ) {
Run Code Online (Sandbox Code Playgroud)
Lor*_*ica 19
您可以想象堆栈从底部开始增长,底部(即第一个推送)元素具有索引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 )
+-----------------------+
Run Code Online (Sandbox Code Playgroud)
您还可以说"正常索引"(从底部索引的索引)是元素的绝对索引(就像C中的数组一样,除了从1开始).相反,负指数与堆栈顶部"相对".lua_gettop
给出堆栈顶部的绝对索引(它始终具有相对索引-1
).
为什么有两种索引堆栈的方法呢?因为有时访问像数组这样的元素很有用(使用绝对索引),有时你只需要访问最后推送的元素(所以从顶部索引).
顺便说一句,我通常想象Lua堆栈的反转:从上面开始向下生长(即堆栈顶部位于我的心理表示的底部).我发现这个心智模型更有用,因为我将索引-1解释为" 在代码中向后退(因此向上),直到找到第一个推送 ".以这种方式,索引-2将" 退回到代码中,直到找到第二次推送 "等等.所有这些都有助于我快速确定我推送的内容.
但是,为了避免混淆,我在这里使用了更经典的表示法,其中堆栈顶部真的在顶部绘制!
来自PIL(http://www.lua.org/pil/24.2.3.html)
请注意,负索引-x等于正索引gettop - x + 1.
因此
if( lua_isfunction(L,lua_gettop(L)) ) {
Run Code Online (Sandbox Code Playgroud)
做同样的事
if( lua_isfunction(L,-1) ) {
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4347 次 |
最近记录: |