Local function as a Parameter in Coroutine

Im trying to wrap my head around how this could work. I basically need a local function as a parameter in a Coroutine. wrap function

Example:

local function SpawnPart()
  local Part = Instance.new("Part")
  Part.Parent = workspace
  --other things
  wait(5)--tween equivalent
  return Part
end

local function DestroyPart(Part)
  Part:Destroy()
end

for i = 0,5,1 do
   coroutine.wrap(DestroyPart)(SpawnPart())
end

In this example, The script spawns one part, tweens it than destroys it, and repeat x5. The Intent is it to spawn 5 parts and tween them at the same time and destroy them a the same time.

I think you could also do

for i = 0,5,1 do
local Part = coroutine.wrap(SpawnPart)()
coroutine.wrap(DestroyPart)(Part)
end

The problem with this though is the function hasn’t returned the part yet and errors when it fails to retrieve it.

So what should I do, the end goal is to tween many parts at once and remove them at the same time. With 2 different functions for spawning and destroying.


local function repeatcode()
   while true do
      local function Destroy(part)
         wait(5)
         part:Destroy()
      end
      wait(0.1)
      local part = Instance.new("Part")
      --PART PROPERTIES HERE
      --TWEEN HERE (I'm not lazy, I just don't know the tween you're going for)
      coroutine.resume(Destroy)
   end
end
coroutine.resume(repeatcode)

Tell me if this doesn’t work.
Incase that doesn’t work, I have an alternative:

local function Destroy(part)
   wait(5)
   part:Destroy()
end

local function repeatcode()
   while true do
      wait(0.1)
      local part = Instance.new("Part")
      --PART PROPERTIES HERE
      --TWEEN HERE (I'm not lazy, I just don't know the tween you're going for)
      coroutine.resume(Destroy)
   end
end
coroutine.resume(repeatcode)

If none of those work, message me back with the output error included.

1 Like

Not so surprisingly after I posted I got the idea for the solution which works similar to yours @Enhanced_Tix but slightly modified to be a but simpler (I think).

local function SpawnPart()
  local Part = Instance.new("Part")
  Part.Parent = workspace
  --other things
  wait(5)--tween equivalent
  return Part
end

local function DestroyPart(Part)
  Part:Destroy()
end

local function RepeatCode()
  local Part = SpawnPart()
  Destroy(Part)
end

for i = 0,5,1 do
  coroutine.wrap(RepeatCode)()
end

Thanks for the help though @Enhanced_Tix : D