How long doesnt a "While True Do" hinder the execution of a script?

sorry if i’m on the wrong topic, but i don’t know where i can post this question:
I always hear that one should never leave a “While True Do” lost in the script because it can hinder its execution.

so I did a test, I created the following script:

game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(c)
		c.Humanoid.Touched:Connect(function(hit)
			print("HIT!") --the script still works without interruption
		end)
	end)
end)


while true do 
	wait()
	print("LOOP")
end

even putting a “while true do” in the script, it still worked. However when I inverted the script, the OnPlayerAdded function did not work

while true do 
	wait()
	print("LOOP")
end


game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(c)
		c.Humanoid.Touched:Connect(function(hit)
			print("HIT!") --the script still works without interruption
		end)
	end)
end)

so I was curious: When does a “While true do” hinder the execution of a script?

2 Likes

The simple answer, indefinitely(unless you put a break in there).


Code executes from top to bottom, left to right. So the script would have to wait for the previous line to finish before executing. To make your second example run, use a coroutine:

coroutine.wrap(function() -- Hello there! I am a coroutine!
    while true do 
	    wait()
	    print("LOOP")
    end
end)()


game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(c)
		c.Humanoid.Touched:Connect(function(hit)
			print("HIT!") --the script still works without interruption
		end)
	end)
end)

Basically what a coroutine is is a script inside of a script.

2 Likes

Lua is single threaded, if you want something to occur (bearably) alongside something else, then use coroutines to run that code in a new thread.

In your script you’re basically looping indefinitely, anything after that won’t technically be allowed to run

while true do wait() end print("does not print")
2 Likes

So if I create a script that has 1000 lines (consisting only of Functions) and at the end of it (line 1001) I add a “While true do”, the script will still continue to work at the same time that this Loop is running without any problem ?

yes, all code that’s before it will run as it’s supposed to

1 Like