Here’s my problem, I have a function that has very long code, but I need to cancel it when a specific event is fired. But I can’t just use an if statement with return, it needs to be cancelled in the precise moment that the event is fired, and since the code is long, I would have to put an if statement in every other line of code for that to even work.
Example:
Main_Function = function()
Event.OnServerEvent:Connect(function()
return --I need something similar to this. This only exits the current thread (this event, and not the whole function)
end)
--Code that yields
end
Main_Function()
I’ve tried coroutines, but there doesn’t seem to be a way to completely end them, you can only yield them, on top of the fact that I would get no error traceback using them.
Is there some kind of way to just end a function like Function:Stop() or something?
Try looking at a promises. You can definitely cancel them.
Coroutines lack the ability to cancel an operation if the value is no longer needed without extraneous manual work at both the call site and the function implementation
Here is an example, the function tween is called then gets canceled internally with the tween inside the function getting canceled:
local function tween(obj, tweenInfo, props)
return Promise.new(function(resolve, reject, onCancel)
local tween = TweenService:Create(obj, tweenInfo, props)
-- Register a callback to be called if the Promise is cancelled.
onCancel(function()
tween:Cancel()
end)
tween.Completed:Connect(resolve)
tween:Play()
end)
end
-- Begin tweening immediately
local promise = tween(workspace.Part, TweenInfo.new(2), { Transparency = 0.5 }):andThen(function()
print("This is never printed.")
end):catch(function()
print("This is never printed.")
end):finally(function()
print("But this *is* printed!")
end)
wait(1)
promise:cancel() -- Cancel the Promise, which cancels the tween.