Built-In Events

Many objects have built-in events provided by their APIs that automatically respond to specific actions or changes related to those objects. For example, a player's Character touching a BasePart automatically fires a Touched event. Most built-in events are synchronous, so you can connect a function to follow custom behaviors in response to an event.

Connecting Functions to Events

You can connect a function to an event using Connect() to execute code each time the event fires. Most events pass arguments to their connected functions when they fire; for example, the BasePart.Touched event passes the object that touched the Part, and the Players.PlayerAdded event passes the Player that joined your experience.

The following code sample demonstrates how to connect a function named onPartTouched() to the Touched event of a BasePart in the Workspace.

Script

local part = workspace.Part
local function onPartTouched(object)
print("Part was touched by", object:GetFullName())
end
-- Connect the above function to the Touched event
part.Touched:Connect(onPartTouched)

You can also connect anonymous functions to events when you want to use variables in the parent scope and you don't need to use the function elsewhere. The following code sample shows how to connect an anonymous function to the Players.PlayerAdded event.

Script

local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
print(player.Name, " joined the experience!")
end)

Disconnecting Functions from Events

In Luau, the Connect() method returns an RBXScriptConnection object. If you connect a function to an event but don't want the function called in subsequent event firings, disconnect it from the event by calling Disconnect() on the RBXScriptConnection object.

The following code sample shows how to connect and disconnect a function to/from the Part.Touched event.

Script

local part = workspace.Part
local targetPart = workspace.TargetPart
-- Declare an empty placeholder variable for the connection
local connection
local function onPartTouched(otherPart)
if otherPart == targetPart then
print("The part hit the target!")
-- Disconnect the connection
connection:Disconnect()
end
end
-- Connect the above function to the Touched event
connection = part.Touched:Connect(onPartTouched)

Waiting for Events to Fire

If you want a script to yield until a specific event fires, use the Wait() method. This method returns the event's arguments which you can assign to variables, such as touchedPart in the following example.

Script

local part = workspace.Part
local touchedPart = part.Touched:Wait()
print("The part was touched by", touchedPart:GetFullName())