开发者

Error handling in Lua using longjmp

开发者 https://www.devze.com 2022-12-20 01:50 出处:网络
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...

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 buf开发者_如何学编程fer 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");


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号