How do I make a "If then" loop?

(Note: Repeat works for now, but if you have any other suggestions- go for it!)

Hey everyone! I’m getting way better at scripting as I go. Recently I was trying to make a “if then” loop! But nothing I’ve seen works. :thinking:
The code in the picture MIGHT be right, but why it doesn’t work could potentially be because of the gui it’s under is disabled.

IfThenLoop

^The blurred out part you don’t need to worry about, it’s just some code that doesn’t relate to it at all.

Any help/suggestions would be appreciated! :happy3:

1 Like
repeat
 --stuff
until
script.Parent.Parent.Enabled == true

or

while wait() do
if script.Parent.Parent.Enabled == true then
--stuff
end
end
-- this while loop will loop infinitely. If you don't want it to loop infinitely make it into a coroutine

I don’t really think a if statement within a repeat is a good choice

1 Like

Not sure what your goal is. Alternatives:

repeat
    -- ...
until not script.Parent.Enabled

while script.Parent.Enabled do
    -- ...
end

Or you can invert the conditions depending on what you want.

2 Likes

If-then tests a condition, it’s not a loop. Repeat, while and for are loop starters. Repeat and while are conditional loops: they continue to run iterations until the condition is met. While checks its condition before starting an iteration, repeat runs at minimum 1 iteration until the condition is met.

If statements are not needed in this case unless it’s deeper into the loop body or you’re checking for something different that isn’t related to terminating the loop you’ve started. Your conditional should be happening after the until part.

I also have no idea why you’re using a loop for enabling something in the first place, even if it’s just for a test, because you don’t need one. You kind of do need to show all your code here because I can’t really understand what you’re doing or why you need to do it, other than you probably don’t need to.

2 Likes

We could help you more if you at least revealed what you were trying to do.

if thing then
--stuff

This code performs “stuff” if thing is true.

elseif thing2 then
--other stuff

This code performs “other stuff” if thing2 is true and thing is not. You can add as many of these as you want after each other.

else
--random stuff

This does random stuff is thing is not true, thing 2 is not true, thing3 and etc are not true. Basically the code’s last option

end

I suggest you learn some more of these statements or buy a book. They explain these really well. There’s also this, which teaches it all:
https://education.roblox.com/en-us/resources/intro-to-coding
Since you’re a little more experienced than beginners, here:
https://education.roblox.com/en-us/resources/intro-to-coding-coding-2-using-if/then-statements

1 Like