性能是一个很好的答案,但我认为它也使代码更易于理解且不易出错。此外,您可以(几乎)确保 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
)。在每种情况下会产生什么结果?
您应该将 Luafor
循环视为对序列的迭代,例如 Python 习惯用法 using (x)range
:
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