当循环正在执行时递减循环计数器 [英] Decrementing a loop counter as loop is executing
问题描述
我试图在循环运行时递减一个for循环的计数器。不幸的是,Lua似乎不允许这样做。这段代码应该永远运行:
for i = 1,100 do
print(i)
i = i - 1
end
事实上, 1-100。这是由设计?如果是这样,我如何减少运行循环的计数器(例如,因为当前的循环被取消资格,应该再次运行)?
这是设计。从 Lua参考手册:
3.3.5 - For语句
在循环开始之前,所有三个控制表达式都只计算一次。所以修改
i
的值就可以了。 循环不会改变循环的运行方式。I'm trying to decrement the counter of a for loop as the loop is running. Unfortunately, Lua doesn't seem to allow that. This piece of code should run forever:
for i = 1, 100 do print (i) i = i - 1 end
but it does, in fact, simply print the series 1-100. Is that by design? If so, how do I decrement the counter of a running loop (for example because the current cycle was disqualified and should run again)?
解决方案It's by design. From Lua reference manual:
3.3.5 – For Statement
All three control expressions are evaluated only once, before the loop starts. They must all result in numbers.
So modifying the value of
i
inside the loop won't change how the loop runs.这篇关于当循环正在执行时递减循环计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!