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.


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

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.


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

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.


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
-- 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.


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