14

我将如何终止 Lua 脚本?现在我遇到了 exit() 的问题,我不知道为什么。(这更像是一个 Minecraft ComputerCraft 问题,因为它使用包含的 API。)这是我的代码:

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
4

7 回答 7

17

正如 prapin 的回答所述,在 Lua 中,该函数os.exit([code])将终止主机程序的执行。然而,这可能不是您想要的,因为调用os.exit不仅会终止您的脚本,还会终止正在运行的父 Lua 实例。

Minecraft ComputerCraft中,调用error()也将完成您正在寻找的内容,但将其用于其他目的而不是在发生错误后真正终止脚本可能不是一个好习惯。

因为在 Lua 中,所有脚本文件也被认为是具有自己作用域的函数,退出脚本的首选方法是使用return关键字,就像从函数返回一样。

像这样:

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
于 2012-10-06T14:38:45.667 回答
4

break语句将跳到它所在的 、 或 循环之后forwhilerepeat

while true do
    if turtle.detect() then
        if turtle.getItemCount(16) == 64 then
            break
        end
        turtle.dig() -- digs block in front of it
    end
end
-- break skips to here

lua: 的一个怪癖break必须出现在 an 之前end,尽管不一定是end你想要跳出的循环的,正如你在这里看到的。

此外,如果您想在循环开始或结束的条件下退出循环,如上所述,通常您可以更改您正在使用的循环以获得类似的效果。例如,在本例中,我们可以将条件放入while循环中:

while turtle.getItemCount(16) < 64 do
  if turtle.detect() then
    turtle.dig()
  end
end

请注意,我在那里稍微改变了行为,因为这个新循环将在达到项目计数限制时立即停止,而不会继续直到detect()再次变为真。

于 2013-10-16T06:59:42.427 回答
3

exit标准 Lua中没有命名全局函数。

但是,有一个os.exit功能。在 Lua 5.1 中,它有一个可选参数,即错误代码。在 Lua 5.2 上,有第二个可选参数,告诉 Lua 状态是否应该在退出之前关闭。

但请注意,Minecraft ComputerCraft可能提供与标准功能不同的功能os.exit

于 2012-10-06T14:19:06.953 回答
3

您也可以通过在海龟/计算机界面中按住Ctrl + T几秒钟来手动终止它。

于 2013-04-23T02:40:51.460 回答
1

不要使用while true

做这样的事情:

running = true
while running do

    -- dig block
        turtle.dig() --digs block in front of it

    -- check your condition and set "running" to false
    if turtle.getItemCount(16) == 64 then
        running = false
    end

end

此外,你不必turtle.detect()在挖掘之前打电话,因为会turtle.dig()在内部再次调用它

于 2016-02-10T14:44:09.913 回答
0

不要使用while true. 而不是它使用这样的东西:

while turtle.getItemCount(16) < 64 do
  if turtle.detect() then
    turtle.dig()
  end
end

它会为你工作。

于 2016-11-19T08:35:33.450 回答
-1

shell.exit() 关闭计算机工艺中的 lua 脚本。欲了解更多信息,请访问http://computercraft.info/wiki/Shell.exit

于 2014-04-10T00:09:09.950 回答