性能是一個很好的答案,但我認爲它也使代碼更容易理解,而且更少出錯。此外,你可以(幾乎)確保for循環總是終止。
想想會發生什麼,如果你寫的是不是:
local a = {"first","second","third","fourth"}
for i=1,#a do
print(i.."th iteration")
if i > 1 then a = {"first"} end
end
你怎麼理解for i=1,#a
?是平等比較(i==#a
時停止)還是不等式比較(停止當i>=#a
)。每種情況下的結果是什麼?
你應該看到的Lua for
環路迭代一個序列,使用(x)range
Python的成語,如:
a = ["first", "second", "third", "fourth"]
for i in range(1,len(a)+1):
print(str(i) + "th iteration")
a = ["first"]
如果你想每次評估條件,你只需要使用while
:
local a = {"first","second","third","fourth"}
local i = 1
while i <= #a do
print(i.."th iteration")
a = {"first"}
i = i + 1
end