问题描述
我正在尝试在循环运行时递减 for 循环的计数器.不幸的是,Lua 似乎不允许这样做.这段代码应该永远运行:
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
但实际上,它只是简单地打印系列 1-100.这是设计的吗?如果是这样,我如何减少正在运行的循环的计数器(例如,因为当前循环被取消资格并应该再次运行)?
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)?
推荐答案
这是设计使然.来自 Lua 参考手册:
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.
因此在循环内修改 i
的值不会改变循环的运行方式.
So modifying the value of i
inside the loop won't change how the loop runs.
这篇关于在循环执行时递减循环计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论