[Solved]Any ways to stop a function?

Okay thank you , now that i know that i can litterally cry and restart my script , have a good day lol.

1 Like

By using tick() and once a specific time past and a debounce is still true/false since it ain’t stopped yet, then print whatever, else if it’s not then, fire return to stop the function.

This works effectively because there’ll be less delays than while loops wait().

Use return. Read this Lua documentation.

1 Like

I’ve come across this problem in depth, actually. The current function you’re using can’t be stopped, you will have to rewrite your code in such a way that it can be. It’s hard to determine what you’re doing and I couldn’t really find it under the mound of repeat posts about return.

You should try switching to an event-based system or rewrite your system a little bit, such as freezing the game state to “Not enough players” until there are enough. You can then use a numeric for loop for a countdown, which can allow you to break the function after each step.

for i = 15, 0, -1 do
    if notEnoughPlayers then
        break
    else
        someTime = i
        wait(1)
    end
end

Or something.

1 Like

Oh hey! I forgot that you could use a for loop with yields to check!

Also note that break will stop the loop instead of the function. Use return, as it will end the function instead, providing the paragraph about what break and return is from the link @slothfulGuy sent earlier.

Example

local Boolean = false -- do something for the boolean to become true

local function StartTimer()
    local i = 0
    repeat -- 20 seconds, you could use the numeric loop addressed above instead of repeat
        if Boolean then
            return
        end
        wait(1/20)
    until i == 20 * 20
    print("Timed out")
end

return basically stops a function, but what if you want to pause it? use coroutine

local ex = coroutine.wrap(function()
wait(1)
print("Test")
coroutine.yield()
wait(2)
print("Test2")
end)
ex()

I haven’t read all of the replies because there are very many, but to stop a thread (a function is part of a thread, if you want to stop a function and not its entire thread then the only way is to return out) you have two options:

  1. either the thread is running and you stop it from itself: coroutine.yield() is the best way
  2. or you have to stop it externally when it is yielded (if other code is running, your thread is either finished or yielded, you can check which via coroutine.status(thread))

the second option is definitely more complex, @Operatik linked my thread specifically about coroutine.kill
I am posting here to add on that on top of one of the hacky functions mentioned in that thread, you can also just destroy the script the thread originated from

23 Likes