parameters - 为什么以及何时我要在 Lua 中使用 os.exit() 函数的参数“代码”
问题描述
在 Lua 文档中,他们说退出脚本时code
参数 in 会os.exit([code])
返回 0 以外的值,例如,如果我运行以下行:
os.exit(7)
它将产生以下输出:
>Exit code: 7
我的问题是为什么以及何时更改脚本的退出值有用?比如,我将在何时何地使用此退出代码“7”?
解决方案
该值返回给运行 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
.
推荐阅读
- python - 使用 random.randint() 屏蔽每个 DataFrame 列
- javascript - 用于查找 2 个文件中内容之间差异的 Java 脚本,包括字体
- asp.net - 如何在asp.net中解决这个为什么结果= 0
- database - 何时使用 Redis?什么时候去塔兰图尔?
- hyperledger-fabric - 我如何运行零知识证明 (ZKP) 以使用 Hyperledger 结构确认块中的数据
- amazon-web-services - AWS CLI v2 不选择环境变量
- angular - FormControl 类型的角打字稿
- android - 回调 JNI C 作为 C 上的参数传递
- django - 将 API 密钥添加到 DRF 可浏览 API 页面中的标头
- reactjs - 在按钮上单击选中复选框并将数据添加到 react redux 中的购物车?