Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would I 'disconnect' a spawn?

Not like a spawnlocation, but a spawn for running while loops in the background, kind of like 'threading'

How would I stop a while loop running in the background?

3 comments

0

sorry if i didnt explain it well enough..

0

So you want to stop the while loop when something changes? or...?

0

No I was just wondering if you could even disconnect a spawn like you can a function..

1 answer

✓ Accepted answer

Yes.

Let me write an example that we can work off of because you didn't

spawn(function()
	while wait() do
		print(math.random())
	end
end)

There are multiple ways we can end this.

  • #1, using break

You can end loops by using the break function. Example,

spawn(function()
	while wait() do
		local num = math.random()
		print(num)
		if num == 0.5 then--Very unlikely
			break
		end
	end
end)

  • #2, using return

You can use return in any function to "end" it.

spawn(function()
	while wait() do
		local num = math.random()
		print(num)
		if num == 0.5 then--Very unlikely
			return
		end
	end
end)
I'm "pretty sure" you can do this

Ending function remotely,

You a variable that can be changed elsewhere in the script and if the variable equals "true" end the function.

local RunningLoop = false

spawn(function()
	RunningLoop = true
	while wait() do
		print(math.random())
		if RunningLoop == false then
			break
		end
	end
end)

game.Workspace.Part.Touched:connect(function(p)
	if p.Name = "ball" then
		RunningLoop = true
	end
end)
The touched event is an example of turning off the loop with a function/event.

If you need something explained further please ask.

Good Luck!

If I helped, please don't forget to accept my answer.

2 comments

1

yeah that helped, i was looking for a keyword tho like maybe despawn() or something lol. thanks though!

0

return

This discussion is preserved as it was. New answers, comments, and votes are closed.