How to end script execution gracefully?
The function error
will raise an error with the given message, and if it is not handled with pcall
will result in a stack trace. This is useful when developing, but does not impress end users. Often people will define a function quit
like so:
function quit(msg, was_error)
io.stderr.write(msg,'\n')
os.exit(was_error and 1 or 0)
end
os.exit
terminates a script immediately, without invoking the garbage collector. (In Lua 5.2 there is an optional second argument to os.exit
which does close the Lua state and force proper cleanup.)
The behaviour of error
can be modified by setting debug.traceback=nil
so that it doesn't produce a stack trace. (This is a nice example of Monkey patching; modifying Lua's operation by changing a library function dynamically.)
This monkey patch also affects the assert
function. assert
takes two arguments, a must-be-true condition and an error message. It is not a statement and returns the first argument. Because Lua functions often return a nil
value and an error string when they fail, the following idiom works because the first argument passed to assert
will be nil
, and the second will be the error string.
f = assert(io.open(file))
Generally users of a module only want to see a stack trace involving their own code, and aren't interested in the internal details of the error (anyone who has used a badly-behaved Java library knows all about this.) The stack trace produced by error
can be controlled by an optional 'level' parameter indicating who on the call stack is to be blamed for the error when generating the error message. A more general solution to this is provided by Lua Carp, modelled on the Perl carp
module.