简体   繁体   中英

Lua C API: Stack empty after pcall error

I have a problem using Lua C API. When pcall (C API function) fail, the error is pushed on the stack. lua_tostring shows an error on the stack but lua_gettop shows says the stack is empty.

#include <lua5.2/lauxlib.h>
#include <lua5.2/lua.h>
#include <lua5.2/lualib.h>

int main()
{
    lua_State *L = luaL_newstate();
    lua_pcall(L, 0, 0, 0);
    printf("%d\n", lua_gettop(L)); // outputs 0, indicating empty stack
    printf("%s\n", lua_tostring(L, -1)); // outputs "attempt to call a nil value", indicating non-empty stack
}

Compile with: gcc main.c `pkg-config --cflags lua5.2` `pkg-config --libs lua5.2`

This program display: 0 attempt to call a nil value

lua_gettop(L) return the stack size. Here I get 0. How can I get a string from an empty stack ?

The behavior is the same with the 5.1 version.

This has been answered in the Lua mailing list. The behavior is correct: you need to push a function onto the stack to call it. The stack after luaL_newstate is empty.

Edit: The OP said "How can I get a string from an empty stack?". My answer is: Why do you want to get something from an empty stack, when you know it is empty since lua_gettop returned 0?

Bottom line:

  • The stack was empty before calling lua_pcall . This is an error. Lua recovered, but you can't count on it.
  • The stack was empty after lua_pcall . Lua thinks so and tells you so via lua_gettop .
  • You should not try to get a value from an empty stack. The string that is printed is just garbage left over by lua_pcall , but you can't count on it.

As far as I know, lua_pcall does not push an error string. Instead, it overwrites the value at the top of the stack (since there should always at least be a function there ;p). Therefore, lua_pcall (or, more correctly, debug.traceback, I believe) blindly overwrites the top of the stack, not modifying the stack pointer.

Therefore, when lua_pcall returns, the value is at the top of the stack, but the stack pointer signifies that the stack is empty (as it was when you called lua_pcall).

I would assume this is a measure to avoid more serious errors (eg if there was memory corruption or an out of memory error, we wouldn't want to be allocating more stack space for the error message would we?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM