Custom :Connect() functions

Is this possible to do with modules? I tried it on my own, it seems to work, no errors:

If it works, please tell me how to set it up correctly!

MODULE:

local moduleq = {}

function moduleq:Connect(func)
print("This is a "..func.." function")
end

return moduleq

LOCALSCRIPT:

local funcLibrary = require(script.Parent.FunctionService)

funcLibrary:Connect(function()
-- Got no errors here.
end)
1 Like

Those aren’t custom :Connect() functions, not in the way that Roblox’s RBXScriptConnection objects work. Those are generic instance methods and can be named anything.

No, this is wrong. But it is possible if you just switch things up.

Use a Lua Signal module (they’re faster than bindables)
Here’s a modified (ever so slightly) version of Stravant’s Batch-Yielded Signal Implementation (sorry I don’t have a link atm)

--[[
BatchSignal
Note: This is literally almost 1:1 with Stravant's original module.
The only difference is that there is absolutely no dictionaries. Only arrays.
Did this improve performance? I don't know! I didn't compare them lol!
]]--

local IdleThread = nil -- Placeholder for an idle thread for signal fires

local function execute(f, ...)
	local ActiveThread = IdleThread
	IdleThread = nil
	f(...)
	IdleThread = ActiveThread
end

local function newThread(...)
	execute(...)
	while true do execute(coroutine.yield()) end
end

local Signal = {} -- Base class
Signal.__index = Signal

local Connection = {} -- Custom Connection implementation
Connection.__index = Connection

function Connection.new(sig, f, nx) -- Connection constructor
	local t = table.create(4)
	t[1],t[2],t[3],t[4] = true,sig,f,nx or false
	setmetatable(t, Connection)
	return t
end

function Signal.new()
	local t = table.create(1)
	t[1] = false
	setmetatable(t, Signal)
	return t
end

-- Define Connection Method(s)

function Connection:Disconnect()
	assert(self[1], "Connection is dead. De-Reference.")
	self[1] = false
	if self[2][1]==self then
		self[2][1]=self[4]
	else
		local t = self[2][1]
		while t and t[4] ~= self do
			t=t[4]
		end
		if t then
			t[4] = self[4]
		end
	end
end

-- Define Signal Method(s)

function Signal:Connect(f)
	local t = Connection.new(self, f, self[1])
	self[1] = t
	return t
end

function Signal:Fire(...)
	local nx = self[1]
	while nx do
		if nx[1] then
			IdleThread = IdleThread or coroutine.create(newThread)
			task.spawn(IdleThread, nx[3], ...)
		end
		nx = nx[4]
	end
end

return Signal

Just put this in a ModuleScript named Signal under your original module, require it in it, and use this for your connections. It should be somewhat easy to understand with a glimpse of the code and the methods.

3 Likes