I am trying to make my own functions in a module script but I do not know if I can call a :Connect() event on my own created function from a module script. Such as this:
Module.FunctionName:Connect(function()
But I do not know if it is possible. I would love to get some help.
--ModuleScript
local module = {}
function module.Create(instance)
instance = Instance.new("Part",workspace)
end
return module
--ServerScript
local Mod = require(game.ReplicatedStorage.ModuleScript)
Mod.Create:Connect(function()
--Code
end)
No, not like that. You would have to use an event.
local module = {}
local event = Instance.new('BindableEvent')
function module.Create(instance)
instance = Instance.new('Part')
instance.Parent = workspace -- try not to use the parent argument in Instance.new, it's a bit slower.
event:Fire()
end
module.Created = event.Event -- use the event signal of the remote event
local mod = require(game.ReplicatedStorage.ModuleScript)
mod.Created:Connect(function()
print('mod.Create was called!')
end)
mod.Create()
You don’t connection functions, you’ll need to use an event instead.
Usually I just use a BindableEvent to make my own events.
local module = {}
function module.myfunc()
local bindable = Instance.new('BindableEvent')
coroutine.wrap(function()
while wait(2) do
bindable:Fire()
end
end)()
return bindable.Event
end
return module
-- script
local module = require(path.to.module)
local event = module.myfunc()
event:Connect(function()
print('Hello world!')
end)
This would print “Hello world!” every 2 seconds.
You don’t need to put that in a coroutine, I said you need to if its inside a loop. Also coroutine.wrap returns a function so you’ll need to call it.