Reputation: 616
In the Lua documentation, they say that the code
parameter in os.exit([code])
returns a value other than 0 when exiting the script, like, if I run the following line:
os.exit(7)
it will produce the following output:
>Exit code: 7
My question is why and when would it be useful to change the exit value of the script? like, when and where would I work with this exit code "7"?
Upvotes: 2
Views: 728
Reputation: 21367
The value is returned to the process that ran the Lua interpreter; the C language has the same facility.
Typically, 0
is returned on the successful execution of a script, and a nonzero value is returned when there is some kind of error. If a Lua script were called from another script, an error code could guide the calling script in handling the error.
In Bash, you can inspect the returned value by checking the $?
shell variable:
$ lua -e "os.exit(7)"
$ echo $?
7
If you call a Lua script from another Lua script using os.execute
, the exit code is the third of three returned values:
handy_script
:
#!/usr/bin/env lua
io.write(string.format("Doing something important...\n"))
os.exit(7)
main_script
:
#!/usr/bin/env lua
b, s, n = os.execute("./handy_script")
io.write(string.format("handy_script returned %s, %s: %d\n", tostring(b), s, n))
$ ./main_script
Doing something important...
handy_script returned nil, exit: 7
The first value returned by os.execute
is the boolean true
if the command was successfully executed, fail
otherwise (as of Lua 5.4, fail
is still equivalent to nil
). The second value returned is the string "exit"
if the command terminated normally, or "signal"
if it was terminated by a signal. The third value returned is the exit code from the call to os.exit()
, here 7
.
Upvotes: 5