How do i make a while loop that doesn't stop the next thread/line

hello, i am trying to make a while loop without using while loop because a while true loop won’t stop unless you break it inside the loop or outside with an if statement and it won’t go to the other threads or the next lines below the loop.
how do i make a loop that repeats over and over without ruining the rest of my code

example:

while true do
	print("hi")
end

print("hello") -- it wont print

Put simply: Put the loop in a another thread.

There are various ways to do this, but the way I find most suitable for me is task.defer()

task.defer(function()
    while true do
        print("hi")
    end
end)

print("hello") -- it WILL print
4 Likes

now how do i stop it without using an if statement because, if i put a wait in the loop its gonna have to wait that many seconds in order to break the loop

local running = false

task.defer(function()
	while true do
		print("hi")
		wait(10) -- has to wait 10 seconds
		if running then -- until it breaks
			break -- doesn't break imminently 
		end
	end
end)

print("hello") -- it does print

wait(1)
running = true

The best method to do that would be to use repeat, since it can check for any condition for it to stop. This is basic concept:

local a = 1

repeat
    print("hi")
    wait()
until a ~= 1
print("a is no longer 1")

But you’re still essentially using an if since you’re checking something. If you want to use while loops you can just use break

while true do
    wait()
    if something then break end
end
1 Like