Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Multiple threads from a single coroutine?

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

✓ Accepted answer

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

1 comment

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.

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

2 comments

0

You could also just spawn that instead of coroutine.resume(coroutine.create(.

0

You should update that to your question and not the answer.

This discussion is preserved as it was. New answers, comments, and votes are closed.