Hey, so I was wondering, can I have a module that creates a coroutine and returns it?
Can it be controlled by the main script? Such as ThisCoroutine.resume() etc?
This returns a new coroutine with an arbitrary body:
return coroutine.create(function()
-- ...
end)
Yeah but can I pass parameters to it?
You can pass arguments to the coroutine’s body when resuming it, yes:
local co = require(path.to.module)
coroutine.resume(co, ...)
Great, just as I needed it to be!
Hey, can the coroutine be recreated after it’s suspended?
Or would that require something like:
local co = function() return require(path.to.module) end
coroutine.resume(co(), ...)
You could use:
local function body()
-- ...
end
return function()
return coroutine.create(body)
end
local coFactory = require(moduleScript)
local co = coFactory()
coroutine.resume(co)
Forgot to mention, I want to use .wrap , would this work?
local function body(a)
-- ...
end
return function()
return coroutine.wrap(body)
end
local coFactory = require(moduleScript)
coFactory(a)
No, you need to call coFactory for it to return the new wrapped coroutine. You then call the wrapped coroutine with any arguments you want to pass:
local coFactory = require(moduleScript)
local coWrap = coFactory()
coWrap(a)
So with this, I could pass a function (anonymous or otherwise) to a ModuleScript and it could create a coroutine and return it?
If you want to do that, the module script would be as follows
return function(FunctionToConvert)
return coroutine.wrap(FunctionToConvert)
end
You simply require the module in another script, and pass the function onto it
Example:
Convertor = require(path.to.module)
local function body(SomeParameter)
Print(SomeParameter)
end
ThisCoroutine = Convertor(body)
ThisCoroutine("JustSomeString")
Note that I’m writing from phone so I couldn’t test it first