首页 > 解决方案 > 你能检查一下我对 lua 堆栈的理解是否正确吗?

问题描述

我正在学习lua。

我不明白为什么这是错误的。

这是我的lua代码

-- lua
Enemy = {
  HP    = 30,
  SPEED = 8,
  POWER = 10
}

这是我的 cpp 代码。它将访问 Enemy 表和每个值。

...
lua_getglobal(L, "Enemy");

/*
    Current virtual stack
    -----------------------------
    [1] or [-1] Enemy table
*/

lua_pushstring(L, "HP");

/*
    Current virtual stack
    -----------------------------
    [2] or [-1] "HP"
    [1] or [-2] Enemy table
*/

lua_gettable(L, 1); // pop key("HP") and push Enemy["HP"]

/*
    Current virtual stack
    -----------------------------
    [2] or [-1] 30(Enemy["HP"])
    [1] or [-2] Enemy table
*/

// using the 30
double dHP = lua_tonumber(L, -1);

// I think that a top of the stack which is 30 will be pop.  
lua_pop(L, -1);  

/*
    Current virtual stack
    -----------------------------
    [1] or [-1] Enemy table
*/

lua_pushstring(L, "SPEED");

/*
    Current virtual stack
    -----------------------------
    [2] or [-1] "SPEED"
    [1] or [-2] Enemy table
*/

lua_gettable(L, -2);

/*
    Current virtual stack
    -----------------------------
    [2] or [-1] 8(Enemy["SPEED"])
    [1] or [-2] Enemy table
*/

// when I use a top of the stack, VS throws the error.
// lua error said that I'm attempting index a nil value. 
double dSpeed = lua_tonumber(L, -1);

如果lua_tonumber弹出该值,则有意义。但没有这样的描述。
我想知道堆栈的哪一部分是错误的。谢谢。

标签: lualua-api

解决方案


lua_pop(L, n)从堆栈中弹出n元素。
所以,lua_pop(L, -1);不是你想要的。


推荐阅读