lua-users home
lua-l archive

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


On Sun, Oct 15, 2006 at 08:02:20AM +1000, Nick Gammon wrote:
> int main (void)
>   {
>   lua_State * L = luaL_newstate ();
>   luaL_openlibs (L);
>   int error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
>                 lua_pcall(L, 0, 0, 0);
>   return 0;
>   } // end of main
> ---------------
> 
> Isn't there a problem here? What if luaL_loadbuffer fails? For  
> example, out of memory? We can simulate a failure with this example  
> program, which in essence does what caused my application to crash  
> recently:

Set the default error handler, using lua_atpanic.  The default is to
print an error and exit(), which is probably not what you want.

> I am familiar with doing lua_pcall to run the code that I ultimately  
> want to run in a safe way, but I usually did something like this:
> 
> lua_getglobal (L, "somefunction");  --> get some function
> lua_pushstring (L, "blah blah");  --> push arguments to function
> lua_pcall (L, 1, 1, 0);  --> call the function
> const char * p = lua_checkstring (L, -1);  --> oops! this might fail

I'd do eg:

const char *p = lua_tostring( L, -1 );
if( p == NULL )
{
    error("somefunction: returned %s, expected a string", ...); // use your error handling of choice
    return -1;
}

I only use lua_checkstring and the like from within C bindings, and
other places which are inside a pcall.

> So really, the whole sequence above should be protected itself by  
> another level of lua_pcall, like I described. Am I right?

You can do it that way, though I think I'd find that cumbersome.  You can
also set a new panic function for the code block:

  lua_CFunction old = lua_atpanic(L, ErrorHandler);
  ...
  lua_atpanic(L, old);

(Remember that you have to longjmp out of a panic handler.)

-- 
Glenn Maynard