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

Why Isn't My Repeat Working?

Asked by 8 years ago

Hello, This may seem rather basic, but I was wondering why my repeat/while isn't working. The thing is, when I change the wait time in the value added to a to a bigger number, it works. Here is the code:

a = 0
repeat
    a = a + 0.1
    wait(0.1)
    print(a)
until a == 1

Also, here is my while loop:

a = 0
while a ~= 1 do
    a = a + 0.1
    wait(0.1)
    print(a)
end

I don't know if it is a problem with my code or Roblox Studio. Thanks for reading!

0
What exactly isn't working about it? Perci1 4988 — 8y

2 answers

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
8 years ago

I added an extra print to your code for testing purposes.

a = 0
repeat
    a = a + 0.1
    wait(0.1)
    print(a, a == 1)
until a == 1

Alright, so now it will both print a and if a equals 1.

Take a look at the output I get:

0.1 false
0.2 false
0.3 false
0.4 false
0.5 false
0.6 false
0.7 false
0.8 false
0.9 false
1 false ---> WHHAAATTTT
1.1 false
...

How is this possible? It prints as 1, but at the same time states it doesn't equal 1.

Well, this is the annoying thing about comparing numbers. I can't seem to find the wiki article that talks about it, but basically a doesn't equal 1.

It's much more likely to equal something like 1.0000041545. This would cause the comparison to be false.

This is why, when comparing numbers, it's much better do use >= and <= for 'greater than or equal to' and 'less than or equal to' respectively. This will allow for numbers slightly greater or slightly less than the number you're comparing it to, so it will be true even with weird decimals.

a = 0
repeat
    a = a + 0.1
    wait(0.1)
    print(a)
until a >= 1
0
That does help, and I will accept this answer, but the strangest thing is that it should be computing exactly 0.1. When it to a = a + 0.2, it does work. I think this is a problem with studio, but for the moment, you solution has helped me. Thanks! yoman1776 85 — 8y
0
Yeah it's really weird and someone smarter than me could explain it more technically. Perci1 4988 — 8y
Ad
Log in to vote
-1
Answered by 8 years ago

It would have gone too fast for you to see, I guess.

Answer this question