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?
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.
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 ?