Adam Pierce
Adam Pierce

Reputation: 34345

Error handling in Lua using longjmp

I'm embedding a Lua interpreter in my current project (written in C) and I am looking for an example of how to handle errors. This is what I have so far...

if(0 != setjmp(jmpbuffer)) /* Where does this buffer come from ? */
{
   printf("Aargh an error!\n");
   return;
}
lua_getfield(L, LUA_GLOBALSINDEX, "myfunction");
lua_call(L, 0, 0);
printf("Lua code ran OK.\n");

The manual just says that errors are thrown using the longjmp function but longjmp needs a buffer. Do I have to supply that or does Lua allocate a buffer? The manual is a bit vague on this.

Upvotes: 3

Views: 2841

Answers (2)

Adam Pierce
Adam Pierce

Reputation: 34345

After some research and some RTFS, I have solved this problem. I have been barking up totally the wrong tree.

Even though the Lua API reference says that longjmp is used for error handling, the longjmp buffer is not exposed through the API at all.

To catch an error in a Lua function, you need to use lua_pcall(). My code example can be rewritten like this and it works:

lua_getfield(L, LUA_GLOBALSINDEX, "myfunction");

if(0 != lua_pcall(L, 0, 0, 0))
   printf("Lua error: %s\n", lua_tostring(L, -1));
else
   printf("Lua code ran OK.\n");

Upvotes: 9

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84149

The jump buffer chain is part of the struct lua_longjmp pointed to by errorJmp field in the per-thread state struct lua_State. This is defined in the Lua core header lstate.h. Here's a cross-referenced Doxygen of the same.

I think (I'm not a Lua expert) you are supposed to use LUAI_TRY macro.

Hope this helps.

Upvotes: -1

Related Questions