2012-10-06 273 views
12

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

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 

回答

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 
+0

啊,谢谢!在这种情况下,帮助了很多 – user1610406

+0

错误()应该可以正常工作,但我还添加了更好实践的解决方案。 – user1704650

+1

谢谢,虽然这不会在Lua程序中的函数调用中起作用。 (我有同样的问题。) –

3

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

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

但是请注意,我的世界ComputerCraft可能会提供一个不同于标准os.exit之一的功能。

+0

'os.exit()'函数不会退出ComputerCraft中的程序。如果你尝试运行它,你会得到一个错误。相反,使用'shell.exit()' http://computercraft.info/wiki/Shell.exit –

1

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

4

break语句将在forwhile,或repeat环是在后跳到行

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的怪癖:breakend之前来得正好,虽然不一定是end你想摆脱的循环,你可以在这里看到。如果你想在循环开始或结束的条件下退出循环,如上所述,通常你可以改变你正在使用的循环来获得类似的效果。例如,在这个例子中,我们可以把条件在while循环:

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

注意,我巧妙地改变行为有点那里,因为这个新的循环,当它击中的项目数量限制会马上停止,直到detect()再次变为真。

0

不使用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()西港岛线叫它再次内部

0

请勿使用while true。而不是它使用这样的东西:

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

它会为你工作。