Lua for循环减少我?奇怪的行为 [英] Lua for loop reduce i? Weird behavior

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

问题描述

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



  1 
0
2
1
3
2
等等

我预计i会在1到0之间变化。一直在增加,就好像我根本没有改变它一样。怎么回事?

我必须不时删除一个表格元素。所以下一步要处理的是我。在C中,我只会在循环内容的末尾写上--i。在卢阿的任何官方方式? :)

解决方案

循环索引( i 一个局部于循环体的变量,所以你对它做的任何修改都不会影响循环条件或下一个被处理的元素(对于 for 循环)。

如果您需要更好地控制索引以删除元素并继续处理,则应使用,而循环形式。有关详情,请参阅声明部分。


Can someone explain me this?

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

Output is:

1
0
2
1
3
2
and so forth

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

解决方案

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

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循环减少我?奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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