How do I stop a function

Basically I need help stopping a function that won’t stop running. Once I fire this function it wont stop running, it doesn’t end whatsoever. I put checks in place and it just doesn’t stop. I also tried using return and break, but I am not quite familiar with them.

The script is just a simple raycast script that makes a part that stretches from the players head to their mouse.
Here is the script:

function laser(no)
	if no == false then
	if player.Character.Humanoid.Health > 0 then
			local mouseray = cam:ViewportPointToRay(mouse.X, mouse.Y)
			local raycastresult = workspace:Raycast(mouseray.Origin, mouseray.Direction * 1000, rayparams)
			local part = Instance.new("Part")
			part.Anchored = true
			if raycastresult then
				print(raycastresult)
				part.Parent = workspace
				part.Position = player.Character.Head.Position
				part.CanCollide = false
				part.CFrame = CFrame.lookAt(part.Position, raycastresult.Position)
				local mag = (raycastresult.Position - player.Character.Head.Position).Magnitude
				part.Size = Vector3.new(1,1,mag)
				part.CFrame = part.CFrame * CFrame.new(0,0,mag/-2)
				local explosion = Instance.new("Explosion")
				explosion.Parent = workspace
				explosion.Position = raycastresult.Position
			end
		end
	end
end

uis.InputBegan:Connect(function(input)
	local fired = false
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		if fired == false then 
			laser(fired)
			print("hi")
			fired = true
			wait(3)
			print("hi2")
			fired = false
		end
		
	end
end)
	

Return stops the function and optionally returns something
Examples:

    function func()
          print("Start")
          return
          print("this would probably error")
    end
function addTogether(... : number) --variadic function (basically has an infinite number of arguments of type number)
	local numbersToAdd = {...}
	local sum = 0
	for i, number in pairs(numbersToAdd) do
		sum += number
	end
	return sum -- stops and returns or outputs the sum
end
local importantNumber = addTogether(6, 9, 4, 2, 0)
print(importantNumber)

Also when do you want it to stop?

You can wrap it into a thread.

i figured it out, the function wasn’t looping. i just put the fired statement inside the function, so it kept switching to false. Thanks for explaining return tho.

your welcome
your welcome
your welcome

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.