How do I use :Connect with a function?
Example:
function test()
print("Function ran")
end
test:Connect(print("Run"))
How do I use :Connect with a function?
Example:
function test()
print("Function ran")
end
test:Connect(print("Run"))
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)
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)
Event:Connect(Foo())