为什么Lua C函数中的参数值会显示在堆栈底部?

以一个简单的Lua C函数为例:

int luacfunc(lua_State *L)
{
    printf("%g\n", lua_tonumber(L, 1) + lua_tonumber(L, 2));
}

在这种情况下,参数以索引12的形式显示。由于正数表示从下往上的堆栈,这意味着参数位于堆栈底部,而不是顶部。

为什么是这样呢?这难道不需要在每个函数调用中移动整个堆栈以为参数腾出空间吗?

点赞
用户106104
用户106104

Lua 堆栈是特定于您的函数调用的。每个 C 函数调用都有自己的“堆栈”(实际上它是一个更大的堆栈的片段,但这对您来说是隐藏的)。您的参数既在顶部又在底部,因为它们是仅有的堆栈内容。

Lua stack is specific to your function call. Each C function call gets its own "stack" (it's actually a slice of a bigger stack, but that's hidden from you). Your arguments are both at the top and at the bottom, because they're the only thing on your stack.
2015-07-30 08:52:50