How do I pass functions with an argument(s) AS an argument?

Pretty straightforward, I have this function here

function doCooldown(Origin)
	Origin.isCooldown.Value = true
	wait(Origin.CooldownTime.Value)
	Origin.isCooldown.Value = false
end

and I want to multithread it with coroutine.wrap(), a function that takes another as an argument.
This needs to be multithreaded since this will run in a script with multiple other Origin objects being affected at the same time.

So now I’m doing
coroutine.wrap(doCooldown(Origin)), but in this code, the argument for coroutine.wrap() is the function firing, not the function with the argument I want to give.

I’ve gotten around this problem with a much worse way, if I remember correctly, by putting the multithreaded inside another function where I can define the arguments prior to the actual multithread

I don’t want to do that, so this problem now appears as an obstacle to the only way I can accomplish this.

2 Likes

This should throw an error because doCooldown() returns void, and coroutine expects a function. It’s possible to pass parameters along the function.

local function fn(arg1, arg2)
	print(arg1, arg2) --> a b
end

coroutine.wrap(fn)("a", "b")
-- which is the same as
local thread = coroutine.wrap(fn)
thread("a", "b")
-- or similar to
local thread = coroutine.create(fn)
coroutine.resume(thread, "a", "b")

Edit. Alternatively new (green) threads can be opened using the task library.

task.spawn(fn, "a", "b")
1 Like

This worked perfectly, thanks for the help!

2 Likes

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