lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 1 March 2016 at 13:56, Tim Hill <drtimhill@gmail.com> wrote:
> My reading of section 4.6 of the (5.3) reference is that many Lua APIs can raise an error (for example, as a result of a memory allocation failure), which means that these APIs are not guaranteed to return to the caller. This also presumably applies to any Lua APIs that call metamethods that in turn raise errors.
>
> This model is causing us huge problems in any C functions that have to manage resources such as heap memory. I cannot see any way to guarantee that these resources are freed should an error occur (except for lua_call(), which can be replaced with lua_pcall()).
>
> One option appears to be to use C++ try to catch the error, but much of our code if legacy C, and retrofitting it for C++ is something I’d like to avoid if possible. The only way I can see of doing this is to have each C function coded as a “shell” function that then uses lua_pcall() to call *another* C function to do the work, thus setting up a protected environment for the C function so raised errors care caught locally, and this approach seems cumbersome to say the least, nor the least because the shared resources must be managed in the content of the “shell” function so that they can be cleaned up on an error.
>
> How do other people here handle this?

When the function you're dealing with cannot handle being longjmpd out
of, don't use the functions that can raise an error.
These are annotated in the manual with "e" (or "m").

If you need to call a user callback, call it via lua_pcall.

If for some reason you need to call a C API that may throw: push a
luaCFunction (lua_pushcfunction), then lua_pcall it.
(or in lua 5.1 you'll need to use lua_cpcall instead).