Catching syntax errors.

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Catching syntax errors.

Steve Goodrich
We are finally really embedding lua into one of our testers in a way
that our end users can access it. A side effect of this is that we need
to be able to recognize when a bad file has been fed to the lua
interpreter and handle the problem gracefully. Is there anyway for the
embedding program to be notified of syntax errors rather than just
printing them to standard error and calling exit().

We are working under DOS.

Thanks

Steve.

Reply | Threaded
Open this post in threaded view
|

Re: Catching syntax errors.

Roberto Ierusalimschy
> [...] Is there anyway for the
> embedding program to be notified of syntax errors rather than just
> printing them to standard error and calling exit().

Sure. Just set the error handler, with "lua_seterrormethod". This function
sets the function to be called when any error ocurrs (such as syntax errors).
A very naive way to do this follows:

  lua_pushnil();
  lua_seterrormethod();  /* set error method to nil -> does nothing on error */
  if (lua_dofile(filename) != 0) {
    /* an error happens when running the file */
    ...

  The new error method doesn't need to be nil. It can be any
function (in Lua or a lua_CFunction), for instace to catch the error
message for future reference.

-- Roberto

PS: Lua never calls "exit()" when a syntax error occurs. Both "lua_dofile"
and "lua_dostring" return a value signaling whether there was an error or
not.

Reply | Threaded
Open this post in threaded view
|

Re: Catching syntax errors.

Steve Dekorte-2
In reply to this post by Steve Goodrich
>Is there anyway for the
>embedding program to be notified of syntax errors rather than just
>printing them to standard error and calling exit().

Yes. Override the error function using a hook and have it call a C function.
That's how I'm doing just that in my Lua development environment.

This will work for any kind of error, not just syntax errors.

Steve