Using :connect() with functions

How do I use :Connect with a function?

Example:

function test()
	print("Function ran")
end

test:Connect(print("Run"))
1 Like

Just use the function name without parentheses

function test()
   print("Done")
end

Event:Connect(test)

You can also use ‘anonymous functions’ which are these:

Event:Connect(function()
   print("Done")
end)
1 Like

Connect is used to connect a function to an event. One such example that many are familiar with is the Touched event, which fires when a part’s touched and passes the intersecting part as a parameter to the function.

Part.Touched:Connect(function(OtherPart)
    print("Hey! The other part intersected with me!", OtherPart.Name, "is mean!")
end)

--

local OnTouch(OtherPart)
    print("Hey! The other part intersected with me!", OtherPart.Name, "is mean!")
end

Part.Touched:Connect(OnTouch)

Be careful that you do not use parentheses when using the function in Connect (Event:Connect(Foo())). That doesn’t allow the event to call the function when fired and pass the value to it; it calls the function and gives it nil, whilst Connect is expecting a function.

local function SayHi()
    print("Hi!")
end
local Value = SayHi()
print(Value, type(Value)) -- nil nil

When giving the event/Connect the function, just give it the function’s name to call.

Event:Connect(Foo) :white_check_mark:
Event:Connect(Foo()) :x:

14 Likes