How do I make a function with a tuple input (and be able to use that tuple)?

I’m trying to make a custom “connection” object class so that I can have a system that resembles bindable events without having to flood my game with a lot of random instances. So far, I have a basic system working in under 30 lines to connect functions and call them all through the connection, but now I want to try to pass parameters along.

Here’s the code I use to call connected functions when the event is triggered, where self.Functions is a table containing connected functions:

function Connection:Fire()
	table.foreach(self.Functions,function(index) self.Functions[index]() end)
end

I want to modify it to pass a tuple from the input to the functions in the “Functions” tables, like this:

function Connection:Fire(...)
	table.foreach(self.Functions,function(index) self.Functions[index](...) end)
end

I suppose I could take a table input and unpack it into the functions, but that seems a little messy to do, and learning how to work with tuples will also help me in the future with other functions that call functions.

Well, I don’t really know why you’re using table.foreach unless it’s less resource intensive than using a regular for loop but, you should just be able to pass through ... without needing to pack it and unpack it.

function Connection:Fire(...)
	for _, Function in pairs(self.Functions) do
		Function(...)
	end
end

Edit: You might also want to wrap the functions in a coroutine too to prevent the thread calling the functions to yield.

coroutine.wrap(Function)(...)
2 Likes

Thanks for the help, I’m gonna be honest and say that I just completely forgot that ‘in pairs()’ was a thing, thanks for reminding me that it exists. Also, I’ve rarely used coroutines before, is there any possibility they might mess something up in the stack call or something if I use that here? I’m planning on using this class a lot for communication between different objects in their own methods.

coroutines shouldn’t cause problems most of the time but, errors won’t be displayed.

1 Like