Lua for loop does not do all iterations

2019-06-23 18:52发布

问题:

I am new to lua, and i am using it to automate some tasks in the simulation program femm. In my script i have this type of for loop:

for i=0.1,0.3,0.1
do
  print(i)
end

The problem is it only iterates from 0.1 to 0.2(it does not enter i=0.3).I tried with other values (for example from 0.1 to 0.4) and it works properly. Why does this strange behaviour happen? Is this a floating point number problem?

回答1:

This happens because adding 0.1 to 0.1 three times produces a number that is slightly greater than 0.3. Hence the loop stops before reaching your target end number.

This is the danger of using floating point values for loop iteration. Rewrite the loop in integers instead, and perform a division to get your required number:

for j = 1,3
do
    i = j/10
    print(i)
end

Demo.