How to use coroutine.wrap


local function BindToSave(Plr)
–saving stuff–

for i,v in pairs(game.Players:GetChildren()) do

is this right?

i just wanna know if im using the coroutine.wrap the right way

The function and the argument are separated when using coroutine.wrap. Correct way to use it in this case is coroutine.wrap(BindToSave)(v)

Sure, but why wouldn’t using task.spawn be better?

why? and what is that can you give example? is it the same as spawn(function() end)

quick question, it will run instantly unlike coroutine.create right?

task.spawn is the newer version of spawn.

It creates a coroutine and immediately resumes it. spawn works like task.defer, which means it creates a coroutine and resumes it in the next task cycle (you could learn about how the Roblox task scheduler works but to keep this brief, I will not elaborate). But task.spawn resumes it immediately.

The following two pieces of code execute identically:



coroutine.wrap is just a wrapper for coroutine.create. As in, it works like this:

function coroutine.wrap(f)
    local co = coroutine.create(f)
    return function(...)
        return coroutine.resume(co, ...)

last question about the example you showed,
in my case i should use task.spawn(BindToSave(v)) right?

Close, but not quite.

The arguments for task.spawn are:

  • thread or function - Thread to spawn
  • … (varargs) - Arguments to pass into rhat function

What you are doing is calling BindToSave with v and passing the return value (I assume nil) into spawn.

Instead, try this:

task.spawn(BindToSave, v)

got it, thanks il use that instead

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.