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

Is there a proper way to stop a function?

Is there a way to stop a function, outside of a function? Something like this.

local hum = game.Players.LocalPlayer.Character.Humanoid

function fish()
	print("yes")
	wait(1)
	print("no")
	wait(1)
	print("yes")
	wait(1)
	print("no")
end)

spawn(function()
	fish()
end)

hum.Died:connect(function()
	fish:stop() -- ??
end)

This script is an example. ;-;

2 comments

0

Try looking at coroutines. https://www.lua.org/pil/9.1.html

0

You can use spawn(fish) if fish takes no arguments

1 answer

✓ Accepted answer

Something like:

local player = game:GetService('Players').LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local hum = char:FindFirstChildWhichIsA('Humanoid')

function startFish()
	local stop = false

	spawn(function()
		if stop then return end
		print('yes')
		wait(1)
		if stop then return end
		print('no')
		wait(1)
		if stop then return end
		print('yes')
		wait(1)
		if stop then return end
		print('no')
	end)

	return function() stop = true end
end

local stopFish = startFish()

hum.Died:connect(stopFish)

Explanation:

  • We use a "startFish" function that spawns and returns semi-immediately (yielding until the function is completed for something that lets us stop it in the middle is a bit useless)
  • Inside, we have a local variable inside that function that tells that particular instance to stop
  • Lots of checks inside the spawned function (waits are harmless, I strongly recommend putting the "breakpoints" right before the actions rather than before the waits)
  • startFish returns a function you can use to ensure no other things are printed

c:

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