Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to stop a couroutine from outside of it, without the same coroutine yielding?

Asked by
Ribasu 127
5 years ago
Edited 5 years ago

How to stop a couroutine from outside of it AND without yielding it? Yes, one can call yield for it to stop but this can only be done inside of the function. How can I stop the coroutine execution from outside of it? StackOverflow has a nice example of my situationi here: https://stackoverflow.com/questions/21863583/how-to-end-a-looping-coroutine-in-lua. The popular solution is to use debug.sethook but this is difficult to implement (1) as it still needs the coroutine to yield and (2) debug.sethook is not available in Roblox's version of Lua to my knowledge.

1 answer

Log in to vote
1
Answered by
mattscy 3725 Moderation Voter Community Moderator
5 years ago

You may have to implement this without coroutines.

For example, if your coroutine ran a loop that happened every 0.5 seconds, you could instead just call a function that had this same loop (inside of a spawn if you needed a separate thread). Then, that loop could check if it should still be running before every iteration. You shouldn't need the spawn if the loop only starts and stops when a certain event fires.

local Running = false

local function RunLoop()
    Running = true
    spawn(function()
        while Running do
            print("loop has run")
            wait(0.5)
        end
    end)
end

RunLoop()
wait(5)
Running = false --stops the loop

However, if you do it this way, a problem arises. If the loop's wait time is longer than the time it takes to stop and start the loop again, it will start a double loop, printing twice every iteration. So to solve this, you should only need a debounce.

local Running = false
local LoopDebounce = true

local function RunLoop()
    if not LoopDebounce then return end
    LoopDebounce = false
    Running = true
    spawn(function()
        while Running do
            print("loop has run")
            wait(0.5)
        end
    end)
    LoopDebounce = true
end

RunLoop()
wait(5)
Running = false --stops the loop
wait(3)
RunLoop()
wait(0.25) --wait time that is shorter than loop wait time now does not create duplicate loops
Running = false

Hope this helps!

0
Thanks, it's a nice solution, especially since there doesn't seem to be much support for a better one through Lua :/ Ribasu 127 — 5y
Ad

Answer this question