How could I Connect a function to module data

Hello there, I am creating a script with a module where I want to connect a function to a module value for example:

   Module script:

    local Main = {}
 
    Main.GetPlayers = function()
           print("Players")
    end


    ServerScript:


    local Module = require(script.Module)
    
   Module.GetPlayers:Connect(function()
           -- Do what I want...
   end)

I want it like how ROBLOX Does there connection service, Any help is appreciated!

Firstly, ensure that your ModuleScript is returning the array of functions you’re defining in the script. For example:

local Functions = {}

function Functions.Function(...)
     (...)
end

-- Important bit below
return Functions

This means that the variable you’re using to require the module will in turn be the array of functions. To my knowledge, there is no way to utilise the Connect method with methods returned in arrays. Instead, you need to use methods assigned to Roblox data models like usual.

For example:

-- In ModuleScript
local Functions = {}

function Functions.PlayerConnected(...)
    -- Your code
end

return Functions

-- In other runtime scripts
local Module = require(ModuleScript)

function PlayerAdded(Player)
    Module.PlayerConnected(...)
end

game.Players.PlayerAdded:Connect(PlayerAdded)

So we’re using the PlayerAdded method from the Players data model to listen for a new connection, as usual, and calling up our pre-defined function when we detect a player joining.

Hope this helps,
-Tom :slight_smile:

1 Like

Oh, So you cannot Do:

   Module.Function:Connect(function()
   end)

?

Connect is a function of RBXScriptSignal, which cannot be created. However it is possible to create this with a deprecated function.

I don’t think so, the Connect method is often unique to certain functions that are build inside of different object classes. For example, you can’t connect the “Touched” event to a ClickDetector object but you can a BasePart.

As these are built in functions, you can connect functions with them because they are what are known as listeners when listen for an event and trigger a function from there.

From my knowledge, it isn’t possible to create custom listeners using only code. One way around this though, would be to utilise these: BindableEvent | Documentation - Roblox Creator Hub.

Where you can control your events and attach the “Connect” listener to the Event object. Although I’m not entirely sure this would be good for you’re trying to achieve.

Hope this helps,
-Tom :slight_smile:

1 Like

Alright! thank u for your help.

1 Like

If I’ve solved your question, clicking the checkbox icon will mark it as a solution. This helps me and also lets other people know this problem has been resolved.

-Tom :slight_smile:

1 Like