While playing with loops, I've realized that some inputs for a while loop end too soon or never stop at all, even though the expression in the while loop satisfies.
local i = 0 while i~=1 do wait() print(i) i = i+0.01 end ``
Now, let's take a look at this loop and examine it. What it should do is increment i by 0.01, until i should equal 1. Now, of course, this loop should end, because i will become 1 at some point. But after running this program, it doesn't stop. It just continues incrementing i by 0.01. Looking at the command output, it is printing things over 1, and at one point it did print 1, but still it didn't stop.
local i = 0 while i~=1 do wait() local j = i==1 print(i .. tostring(j)) i = i+0.01 end``
To confirm this, I've placed variable j, storing the boolean expression i==1, and then it prints the result alongside i. From again examining this, if i is 1, then of course it is equal to 1 and j should store true, and at the end would print 1true. But again, this is not the case. Instead, it would print 1false, meaning there is something definitely wrong here.
I'm probably going mad, but if someone could confirm if this is in all versions of lua, or if it's just broken with me, please do. I'd also be happy if you could find a workaround :)
I'll be testing it on my end, but there are plenty of work arounds. The best one is the numeric for loop, which you can find here (Personally it's my favorite loop.)
Another way might be to change i ~= 1
to i <= 1
in your while loop.
This most likely (if there's not another problem) is due to a rounding/float issue in Lua. But yes, I highly suggest using the numeric for. It's more advantageous and it gets even more so when you learn to iterate.