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

Remotely Terminating Threads?

Asked by 9 years ago

I'm using coroutines with loops in them, and I want to remotely terminate a coroutine while it's running. What I mean by that is I want to stop it completely outside of that thread, meaning I can't use something like coroutine.yield or a conditional in the running coroutine. Any help? The only solution I can think of is using a seperate script to emulate a coroutine, and destroy that script when I want the thread to stop. This seems ineffecient and messy though. Any ideas or links are appreciated, thanks!

2 answers

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

You cannot do this, because this is not in the spirit of threads, and it's definitely not in the spirit of cooperative execution, which is what coroutines are.

A coroutine has to choose to stop itself. This is because it's not necessarily clear where it's "OK" to stop -- what if it is half-way done with something important, and stopping it there will break everything?

It needs to choose to stop itself -- however, you can make it consult some flag that other scripts can command that will make it choose to stop:

function launch(stopper)
    spawn(function()
        repeat
            wait()
            print(math.random())
        until stopper.stop
    end)
end


s = {}
launch(s)

wait(5)
s.stop = true

The above creates a background loop that goes until stop is set on its argument, which is done after 5 seconds pass.

0
I already knew about this method, but it doesn't really work fro what I'm trying to accomplish. Thanks anyways. aquathorn321 858 — 9y
0
I was dumber when I posted this lmao aquathorn321 858 — 4y
Ad
Log in to vote
1
Answered by 9 years ago

Coroutines will stop if the loop finishes. So create a variable outside of the coroutine function and change it to complete the loop.

For example:

function foo()
    local run = true;
    local c = coroutine.wrap(function()
        while run do
            wait(1)
            print("foo");
        end
    end)

    c();

    wait(10);
    run = false;
end

If done right, you can send the function and change the value at a different time to stop it. You can make the variable global or adjust the scope to suit your needs.

Answer this question