What is the difference between these codes?

What is the difference between these codes. I couldn’t find any difference.

While true do
Part.touched:Connect (function()
print("hlo")
end)
end

And

Part.touched:Connect(function()
While true do
print("hlo")
end
end)   
4 Likes

Top one will most likely crash

bottom will print out “hlo” infinitely when the part is touched

Hmm ? Can u clarify it clearly

top one seems that it has no deley and will create a function to say “hello” when a part is touched
and it does that every second. so if it manages to not crash then when the part is touched it will print out “hlo” mostlikely more then 1000000 times

the bottom one will infinitely print out “hlo” when the part is touched because theres a loop which prints out “hlo” inside the touch function.

Error: No amount of time put to repeat the loop
Note: While true do not needed, since the part runs itself when it was touched

Error: No amount of time placed to repeat the loop
Note: while true do not needed, if no wait time

So what if I want to loop printing “hlo” when touched even triggers and stops when touch is ended??

you can make a variable which tells the loop if it can spam print a word, For example:

local DoLoop = false

BasePart.Touched:Connect(function()
DoLoop = true
BasePart.TouchedEnded:Wait()
DoLoop = false
end)

while wait() do
if DoLoop then
print("hlo")
end
end
1 Like

I’m making an automatic gun that’s why I asked

local Touched = false

Part.Touched:Connect(function()
   Touching = true
)

Part.TouchEnded:Connect(function()
   Touching = false
)

while true do
   if Touched == true then
      print("hlo")
   end
end
local part = script.Parent -- or replace this to part's location
local hold = false -- dont change
local rate = .1 -- cooldown

part.BrickColor = BrickColor.new('Really red') -- temp line for testing
part.Touched:Connect(function() -- connection
	hold = true
	part.BrickColor = BrickColor.new('Lime green') -- temp line for testing
	
	while hold do -- loop idk why i add this
		task.wait(rate)
		print('hi') -- temp line for testing
		hold = false
		part.BrickColor = BrickColor.new('Really red') -- temp line for testing
	end
end)
local UIS = game:GetService('UserInputService')
local key = Enum.UserInputType.MouseButton1
local firerate = 0.1
local fired = false

UIS.InputBegan:Connect(function(input, GPE)
	if GPE then return end
	
	if input.UserInputType == key then
		fired = true
		
		while fired do
			task.wait(firerate)
			print('hi')
		end
	end
end)

UIS.InputEnded:Connect(function(input, GPE)
	if GPE then return end
	
	if input.UserInputType == key then fired = false end
end)