views:

283

answers:

2

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.

A: 

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.

Nikolai N Fetissov
Hmmm, I might be barking up the wrong tree with this, after doing some RTFS, I think the whole setjmp/longjmp thing might be internal within Lua. Maybe errors are handled some other way I've yet to work out. I'm still investigating.
Adam Pierce
OK, I solved it. I need to use the lua_pcall function if I want to catch errors.
Adam Pierce
+4  A: 

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");
Adam Pierce