Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Difference in for loops?

Asked by 8 years ago

Alright, this is fairly easy but I can't seem to figure it out. How do you change whether, in a for loop, the increment is less than/greater than/ less than or equal to/ greater than or equal to. This is NOT an infinite loop, look closely!

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

--Doesn't print 1 at the end, how do i fix this other than setting the second value to 0.8?

1 answer

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

This is a problem with numbers on our computer not having infinite precision. When you write 0.1, it doesn't actually store is as "one tenth". It stores it as a base-2 approximation of 0.1, which is something like this:

0.10000000000000000555111512312578

That means the number you get after you get just around 1 is about 20 * .00000000000000000555111512312578 under 1, so it declares the loop over.


The simplest solution is to use integers, and divide on the inside:

for I = 50, 10, -2 do
    local i = I * 0.1
end

Depending on what you are doing, other options might make sense. For example, if you're doing something like an animation, you could not worry about the for loop altogether and just use the time:

local start = tick()
local duration = 4 -- (seconds)
while tick() < start + duration do
    local time = tick() - start
    local progress = time / duration
    -- do stuff based on progress (which is 0 to 1)

    wait()
end
0
makes sense :) dang .111111111 numbers dragonkeeper467 453 — 8y
Ad

Answer this question