So I’m looking to use coroutines for a light cycle I have- once it turns night time, all the lights need to have some smooth transition, so I was planning to have said coroutine run a little smoothly timed transition, probably in a for loop with a small wait time.
I was looking through coroutines and decided to use coroutine.wrap() and set that up as a function (“TurnOn”). However, trying to run this multiple times yields “cannot resume dead thread”.
This has caused me to come about a few questions that would be nice answered:
Can I not use a .wrap() coroutine multiple times? If I can, how would I go about doing this?
Once a coroutine is “dead” does that mean it is no longer running, at all, so I can create a new one without performance hits of a continously running thread?
Is it bad to have a few coroutines- because of the issue, I made it so that it creates a new “TurnOn” coroutine.wrap() each time it needs to be ran on another thread, but I was thinking that this would be bad, performance wise
You can use coroutines several times, I use them a lot. What I generally do is something like this
local a = coroutine.wrap(function() -- i tend to name it a since i generally only need to run it once
-- do stuff
end)
a() -- call the coroutine
A coroutine dies when it completes itself without yielding. You can create a new one.
I don’t think they’re bad for performance. In my eyes it seems better since it runs faster.
Coroutines are very useful. Let me give you one example. In one of my gun scripts, I have the gun shoot the ray and right before I do the damage stuff I setup and call a coroutine the formats the visible part. I do this so it doesn’t yield the code and the script can go on and calculate damage while the player gets the feedback they need.
If you want to call this multiple times, this is probably what I would do
local function FadeIn()
local a = coroutine.wrap(function()
print("Fading On")
wait(2)
print("Fading Off")
end)
a()
end
FadeIn()
The reason why I put it in a function is that so it makes the coroutine again so we don’t get the dead coroutine error since you need to call this several times. If you have any other questions, feel free to ask!
Once a thread is dead you can no longer resume it. A thread becomes dead once it returns from the function or the function ends.
Using several threads shouldn’t be an issue, but you may want to re use the threads.
You can create a coroutine which you can call an unlimited amount of time with a while true do loop.
local coro = coroutine.wrap(function(arg)
while true do
--logic
arg = coroutine.yield(--[[returns for the function]])
end
end)
If you need a new thread, just create a new thread. If each thread is cheap (in terms of performance), you can have atleast a thousand without any issues. (just make sure they don’t stay around forever so you don’t get a memory leak)