I was trying to make a timer for my game, everything works well but when the loop is a about to end it gives me a really long number that isn’t possible with the loop’s code
here is the loop:
for i = 3 , 0 , -0.1 do
wait(0.1)
print(i)
if i >= 0.1 then
timer.Text = i
end
end
Here is the number if you want to know: 0.099999999999998.
This is the nature of for loops and using a decimal as an increment 0.1, Floating point numbers will occur so you won’t get the number 1 for example, you will get 0.99999999999 which is close to 1 but not.
Additionally, using for loops for a timer is …not a good idea as it assumes that wait(0.1) will wait exactly 0.1 seconds which is 100% false as it will wait for 0.1 or above seconds such as 0.111.
Consequently, I recommend using the delta time returned by wait() to compensate for it like the example code piece below:
local Excess = 0
local Interval = 0.1 -- how often it gets updated
local Total = 0
local Length = 60 -- length of timer
TextElement.Text = Total
while Total < Length do
Total += wait(Interval-Excess)
Excess = Total%Interval
TextElement.Text = math.min(Total-Excess,Length)
end