首页 > 解决方案 > 为什么以及何时我要在 Lua 中使用 os.exit() 函数的参数“代码”

问题描述

在 Lua 文档中,他们说退出脚本时code参数 in 会os.exit([code])返回 0 以外的值,例如,如果我运行以下行:

os.exit(7)

它将产生以下输出:

>Exit code: 7

我的问题是为什么以及何时更改脚本的退出值有用?比如,我将在何时何地使用此退出代码“7”?

标签: parametersluaoperating-systemexit

解决方案


该值返回给运行 Lua 解释器的进程;C 语言具有相同的功能。

通常,0在成功执行脚本时返回,当出现某种错误时返回非零值。如果从另一个脚本调用 Lua 脚本,则错误代码可以指导调用脚本处理错误。

在 Bash 中,您可以通过检查$?shell 变量来检查返回值:

$ lua -e "os.exit(7)"
$ echo $?
7

如果你从另一个 Lua 脚本使用 调用 Lua 脚本os.execute,退出代码是三个返回值中的第三个:

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.


推荐阅读