So while playing around with a coroutine, i have noticed that coroutine.create(), and coroutine.wrap() appear similar, besides the fact it “returns” a function, and is called like a normal function, I was wondering the Difference?
The difference between both of these functions are the uses for them. coroutine.create creates a coroutine but it doesn’t run until coroutine.resume is called
local function test()
return "Success"
end
local TestFunc = coroutine.create(test) -- This won't make the function run
local result = coroutine.resume(TestFunc) -- this will
print(result)
However say you wanted to run this function multiple times. You would need to call coroutine.resume every time you want to run the function. This isn’t the case with coroutine.wrap
local TestFunc = coroutine.wrap(test)
print(TestFunc())
print(TestFunc())
-- Runs each time
Think of coroutine.resume as like a pcall for coroutines. If you want more control over the
coroutine like returning true if it yields else false then coroutine.resume is the right way to go.
If you want a basic coroutine that just runs whenever you call it then coroutine.wrap is the right
way to go.
This is only a basic explanation for coroutines, if you want more information read this document: Coroutines
From what I’m reading, coroutine.wrap “Think of it as a type of pcall?”
The thing is, running coroutine.create, and coroutine.wrap more than once doesn’t actually repeat the code, it instead gives an error: cannot resume dead coroutine
meaning what you are saying isn’t true (unless i (or you) forgot something), this is the code i tried:
local function test()
return "Success"
end
local TestFunc = coroutine.wrap(test)
print(TestFunc())
print(TestFunc())
This Provides barley anymore info then what was already there
So there’s not much difference between the 2 functions they’re basically almost the same thing. The only difference are in yields.
Basically yields are like a temporary stop to a function which can later be resumed.
Here’s an example:
local function test()
coroutine.yield("first")
return "second"
end
local TestFunc = coroutine.create(test)
print(coroutine.resume(TestFunc)) -- true, first
print(coroutine.resume(TestFunc)) -- true, second
Whenever you call coroutine.resume on this function it will return first and that’s where the coroutine will stop until it’s resumed again. This it where it returns second
With coroutine.wrap you don’t need to create or resume a coroutine
local function test(...)
coroutine.yield("first")
return "second"
end
local TestFunc = coroutine.wrap(test)
print(TestFunc()) -- first
print(TestFunc()) -- second
This code does the same thing as the first one but without resuming
I already know this, it only temporarily pauses the code until called again, the only way i know of to keep a coroutine running. Is having a loop inside it, but is there a way to always make it run when called