So I have two event handling issues where there is a nested function like so:
local function foo()
local function baz()
return -- I want this function to also return or break foo()
end
end
But as expected, it terminates baz() which is completly useless because the point of baz() is to stop foo() from running. How can I terminate foo() using baz()?
So what you’re asking is how to terminate the foo() thread by using the function baz()?
If thats so,
local function foo()
local function baz()
return -- some value
end
return baz() -- doing this will just return the value that was returned by baz(), ultimately breaking the function
end
I don’t think that’s what OP means. What you’ve done is have foo return the value that baz returns. I think what OP wants is for baz to stop the foo function at any given time. I’d say it depends on what’s happening in foo. You could have a condition like
local function foo()
local done = false
local function baz()
done = true
end
baz()
while not done do
RunService.Heartbeat:Wait()
end
end
But all that’s doing is busy waiting and foo could have something else it needs to do. Another option would be to fire a bindable inside baz and have foo wait for that bindable to be fired. Altho I think that’s technically still busy waiting.
Thats exactly what I avoided, using any sort of loop because that will halt the thread that called it until a result is ready to be returned. The OP wanted to break the foo() function whenever baz() was called. BindableEvents would’ve been way faster in your case if the OP is okay with a halting thread. However in my case, it does the job as well but has to be used differently compared to yours.
Ah ok. Yea it really just depends on what’s happening in foo because your version of foo can’t execute any other code after calling baz. Some more details from @bootsareme would be helpful.
Judging by the way the OP worded his/her request, they want to terminate the foo() function when baz() is called, which is exactly what my function does.
local endFunction = Instance.new("BindableEvent")
local function foo()
endFunction.Event:Connect(function()
coroutine.yield()
end)
-- lalalala some code here, come code there
endFunction:Fire() -- :o lets stop this function from running
end