【问题标题】:Can you check what I understood about lua stack is right?你能检查一下我对 lua 堆栈的理解是否正确吗?
【发布时间】:2021-05-19 04:32:15
【问题描述】:

我正在学习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 弹出该值,则有意义。但没有这样的描述。
我想知道堆栈的哪一部分出错了。谢谢。

【问题讨论】:

    标签: lua lua-api


    【解决方案1】:

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

    【讨论】:

    • 天哪.. 在这种情况下,我的英语是问题所在。我理解 [n] 元素。谢谢!
    猜你喜欢
    • 2021-12-04
    • 2015-11-15
    • 2010-11-04
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    相关资源
    最近更新 更多