本文介绍了Lua for 循环减少我?奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下吗?

for i = 1, 5 do
  print(i)
  i = i - 1
  print(i)
end

输出为:

1
0
2
1
3
2
and so forth

我预计 i 会在 1 和 0 之间改变.但显然它一直在增加,就好像我根本没有改变它一样.怎么回事?

I exspected i to alter between 1 and 0. But obviously it keeps increasing as if I did not change it at all. What's going on?

我必须时不时地删除第 i 个表格元素.所以下一个要处理的元素将再次是 i .在 C 中,我只会在循环内容的末尾写 --i.lua中的任何官方方式?:)

I have to delete an i'th table element every now and then. So the next element to process would be i again. In C I would just write --i at the end of my loop content. Any official way in lua? :)

推荐答案

循环索引(在您的情况下为i)是循环体的局部变量,因此您对它对循环条件或正在处理的下一个元素没有影响(对于 for 循环).

The loop index (i in your case) is a variable local to the body of the loop, so any modifications you do to it have no effect on the loop conditions or the next element being processed (for the for loop).

如果您需要更好地控制索引以删除元素并继续处理,则应使用while 循环形式.详情请参阅For Statement部分.

If you need to have better control over the index to delete elements and keep processing, you should use the while loop form. See For Statement section for details.

这篇关于Lua for 循环减少我?奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 00:10