当循环正在执行时递减循环计数器 [英] Decrementing a loop counter as loop is executing

查看:182
本文介绍了当循环正在执行时递减循环计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在循环运行时递减一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆