Coroutine erroring after it dies

My code works fine, but throws an error after the coroutine dies, and I can’t figure out why.
These are the relevant parts of the script:

function tween(coin,pos)
	local T = tweenservice:Create(coin, TweenInfo.new(tweenTime, Enum.EasingStyle.Quint, Enum.EasingDirection.Out), {Position = pos, Transparency = 1}) T:Play()
	T.Completed:Wait()
	coin:Destroy()
end


root = script.Parent.HumanoidRootPart
root.Touched:Connect(function(touchedObject)
	if touchedObject.Name == "Hitbox" then
		touchedObject.CanTouch = false
		touchedObject.Parent.CanCollide = false
		local plr = players:GetPlayerFromCharacter(root.Parent)
		plr.leaderstats.Coins.Value += touchedObject.Parent.Parent.Worth.Value
		coroutine.wrap(tween(touchedObject.Parent, root.Position)) -- Erroring line here
	end
end)
1 Like

Could you show me what the error says?

Workspace.Nolas154.Coins:36: missing argument #1 to ‘wrap’ (function expected) - Coins:36

an easy fix would be to do

coroutine.wrap(function()
    tween(touchedObject.Parent, root.Position)
end)()

fixed it, thank you!
What exactly does the ‘()’ at ‘end)()’ do? Don’t really understand that

Honestly i haven’t looked into it myself, But without the () after end) it won’t run.

‘()’ is for calling functions, coroutine.wrap returns a function when called, so you just call the function of the returned function of coroutine.wrap

2 Likes

coroutine.wrap() return a function value that is a coroutine wrapped around your desired function, as such you must append () at the end in order to call the returned function, alternatively, you can assign the function somewhere for later use.

local routine = coroutine.wrap(print)
task.wait(1)
routine("Hello world!")