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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With