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

Multiple threads from a single coroutine?

Asked by
ausmel105 140
9 years ago

Am I right by stating I can only have one single instance of a coroutine running at a time? This question may be difficult to interpret, so I have included an example below.

co = coroutine.create(function()
    print("hi scripting helpers")
    wait(10)
end)

for i = 1, 10 do
    coroutine.resume(co)
end

This would only print "hi scripting helpers" once and then error once 10 seconds has elapsed.

How do I go about solving this?

NOTE: This isn't the actual purpose of why I'm asking, I just included this example to make the question easier to understand.

Thanks for your help.

EDIT:

Sorry bit of a noob here, not used to being able to edit my initial question.

I found a more relevant solution to my problem so someone said it would be best if I add it here.

function newcor(arguments)
    coroutine.resume(coroutine.create(function()
        print(arguments)
        wait(10)
    end))
end

for i = 1, 10 do
    newcor("hi scripting helpers")
end

The above example lets me enter in arguments and will run an infinite number of times, even when the original coroutine is still running.

2 answers

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

If you're just using coroutines to schedule threads in parallel, don't use coroutines. Just use delay or spawn.

If you want something to happen every 10 seconds:

function thing()
    print("Hi")
end

while wait(10) do
    spawn( thing )
end

If you want this loop to be on its own thread, then just spawn that:

spawn(function()
    while wait(10) do
        print("Hi")
    end
end)

Resuming the same coroutine multiple times doesn't restart it, it continues from the last coroutine.yield. ... If you're not using coroutines for that purpose, then just stick with spawn -- it's a little easier to understand less information

0
This is probably too advanced for OP, but; the environement in the script Spawn()ing a thread is shared with that Spawn()ed thread, the enviornment of a script creating a coroutine is *not* shared with that coroutine. adark 5487 — 9y
Ad
Log in to vote
1
Answered by
ausmel105 140
9 years ago

Alright, I found a more relevant solution to my problem, and this lets me enter arguments too.

function newcor(arguments)
    coroutine.resume(coroutine.create(function()
        print(arguments)
        wait(10)
    end))
end

for i = 1, 10 do
    newcor("hi scripting helpers")
end
0
You could also just `spawn` that instead of `coroutine.resume(coroutine.create(`. BlueTaslem 18071 — 9y
0
You should update that to your question and not the answer. alphawolvess 1784 — 9y

Answer this question