如何终止Lua脚本? [英] How to terminate Lua script?
问题描述
我将如何终止Lua脚本?现在,我在使用exit()时遇到问题,我也不知道为什么. (这更多的是Minecraft ComputerCraft问题,因为它使用了随附的API.)这是我的代码:
How would I terminate a Lua script? Right now I'm having problems with exit(), and I don't know why. (This is more of a Minecraft ComputerCraft question, since it uses the APIs included.) Here is my code:
while true do
if turtle.detect() then
if turtle.getItemCount(16) == 64 then
exit() --here is where I get problems
end
turtle.dig() --digs block in front of it
end
end
推荐答案
正如prapin的回答所述,在Lua中,函数os.exit([code])
将终止主机程序的执行.但是,这可能并不是您想要的,因为调用os.exit
不仅会终止您的脚本,还会终止正在运行的父级Lua实例.
As prapin's answer states, in Lua the function os.exit([code])
will terminate the execution of the host program. This, however, may not be what you're looking for, because calling os.exit
will terminate not only your script, but also the parent Lua instances that are running.
在 Minecraft ComputerCraft 中,调用error()
也会完成您要查找的内容,但是将其用于除发生错误后真正终止脚本之外的其他目的,可能不是一个好习惯
In Minecraft ComputerCraft, calling error()
will also accomplish what you're looking for, but using it for other purposes than genuinely terminating the script after an error has occurred is probably not a good practice.
由于在Lua中,所有脚本文件也被视为具有各自作用域的函数,因此退出脚本的首选方法是使用return
关键字,就像从函数中返回一样.
Because in Lua all script files are also considered functions having their own scope, the preferred way to exit your script would be to use the return
keyword, just like you return from functions.
赞:
while true do
if turtle.detect() then
if turtle.getItemCount(16) == 64 then
return -- exit from the script and return to the caller
end
turtle.dig() --digs block in front of it
end
end
这篇关于如何终止Lua脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!