Reputation: 21
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.
Upvotes: 2
Views: 1480
Reputation: 640
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 (e.g. 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?).
Upvotes: 0
Reputation: 72312
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:
lua_pcall
. This is an error. Lua recovered, but you can't count on it.lua_pcall
. Lua thinks so and tells you so via lua_gettop
.lua_pcall
, but you can't count on it.Upvotes: 1