What do you want to achieve? Keep it simple and clear!
I want to end a current function that is running under a certain condition
What is the issue? Include screenshots / videos if possible!
I want to make sure the function ends as soon as the condition is met (not end it by checking after every second), but I do not know if there is some existing method or code that does this.
What solutions have you tried so far? Did you look for solutions on the Developer Hub?
Since I know that wait() provides the smallest amount of time of 0.03 second yield, I used a for loop to calculate each and every 0.03 seconds to check whether that certain condition is met. This solution I came up with is similar to this developer’s problem’s solution How can i break a function while it's running? - #10 by CheekySquid, but of course, I wanted to end the moment that condition is hit.
local function someCode()
while true do
-- Long list of code here
-- The following code below demonstrate the cooldown equivalent to wait(seconds)
for i = 1, 20 * RELOAD_TIME do -- 0.05 * 20 is equivalent to 1 second
wait(0.05)
if IS_EQUIPPED == false or RELOADING_STATUS == false then
-- end this entire function
return
end
end
end
I know how to run a function inside a script, but I was asking if there was a way to end the script as soon as the condition is met without having to check every 0.05 seconds through a loop.
Checking the condition in the while loop should already do the trick as the code won’t run anymore since it fails that check.
However, if you really want it to be instant, I think you could either use events or spawn the function as a thread (using task.spawn()) and then cancel it using task.cancel() once the condition changes?