在循环执行时递减循环计数器

编程入门 行业动态 更新时间:2024-10-27 14:32:15
本文介绍了在循环执行时递减循环计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在循环运行时递减 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:关键词]

本文发布于:2023-03-29 03:33:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/747837.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计数器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!