为什么以及何时我要在 Lua 中使用 os.exit() 函数的参数 "code"

Why and when im gonna use the parameter "code" of the os.exit() function in Lua

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

os.exit(7)

它将产生以下输出:

>Exit code: 7

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

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

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

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

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

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

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

如果命令成功执行,os.execute 返回的第一个值是布尔值 true,否则 fail(从 Lua 5.4 开始,fail 仍然等同于 nil)。如果命令正常终止,则返回的第二个值是字符串 "exit",如果它被信号终止,则返回 "signal"。返回的第三个值是调用 os.exit() 的退出代码,此处为 7.