How to make custom :connect() in modules?

im making my huge ai class, and i wanna make something like OnBlahBlahBlah:execute(function() end), how can i make it?

1 Like

I only saw 1 module do and I don’t know how performent it is but basically use a BindableEvent:

local module =  {}
local event = Instance.new("BindableEvent")

module.called = event.Event

function module.test()
       event:Fire()
end

return module
local test = require(script.ModuleScript)

test.called:Connect(function()
print("Hi")
end)

task.wait(5)

test.test()

Maybe there is another way so dont rely on this way

5 Likes

You can use tables and metatables for that.

local Class = {}
Class.__index = Class 

function Class:new()
    local instance = setmetatable({}, Class)
    return instance
end
function Class:execute(callback)
    if type(callback) == "function" then
        callback()
    else
        error("Expected a function")
    end
end

Usage inside a script:

local Instance = Class:new()

Instance:execute(function()
    print("callback")
end)

:execute method takes the function and executes it.

4 Likes

I’ve been wondering, is going the trouble of making a custom Connection system worth it, or is just using BindableEvents good enough, I used to make my own until I figured you could just use a BindableEvent the same way @yoshicoolTV did, been using BindableEvents ever since and I have noticed no difference, just that custom Objects are much simpler now, is there a reason people still go the extra mile making their own connection system?

1 Like

BindableEvents don’t allow certain arguments to be passed through the .Event Signal (i.e. tables with metatables won’t pass with the metatable); custom implementations exist to work around this

2 Likes

Ah yes, that, recently dealt with that, however if that’s all, then that puts my worries to rest, what I did was basically pass any metatables in a seperate argument, then reset the metatables for the original table

1 Like

That’s about the only negative to using BindableEvents (another reason is just having more customizability)

Roblox article on parameter limitations

2 Likes

I believe this is a result of the fact that, bindableEvents return a shallow copy of the original table, instead of the same table, correct?

1 Like

Interesting, I’ll give this a read, surprising I never saw this before
Edit: I read the article, and I see the reason why people may prefer the latter, thanks for clearing that up

1 Like

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