Decrementing a loop counter as loop is executing

僤鯓⒐⒋嵵緔 提交于 2019-12-01 21:18:16

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/25256037/decrementing-a-loop-counter-as-loop-is-executing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!