2012-10-06 274 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 

它會爲你工作。