Responding to events
Register event callbacks, disconnect handlers, and wait for API events in Luau.
API events are AstScriptSignal values. Connecting a function registers a handler for future events.
Connect a handler
Connect returns an AstScriptConnection.
The event determines the callback arguments. ChildAdded passes the new child.
local connection = workspace.ChildAdded:Connect(function(child)
print(child.Name)
end)Each callback runs on a separate thread. A callback that yields can overlap with
later invocations. Add a guard when overlapping execution would be invalid.
Repeated Connect calls create separate registrations.
Disconnect a handler
Retain the connection and call Disconnect when the handler is no longer needed.
Destroying the source instance disconnects its events. Destroying an instance
captured by a callback does not disconnect a handler on another source.
local connection = workspace.ChildAdded:Connect(function(child)
print(child.Name)
end)
connection:Disconnect()Connected reports whether a connection is active. Disconnection does not
interrupt a callback already running.
Handle one event
Use Once for a single callback invocation. It disconnects before invoking the
callback, including if that callback triggers another event.
workspace.ChildAdded:Once(function(child)
print(child.Name)
end)Use Wait when the current thread must yield until the next event. It returns
the event arguments. Events between successive Wait calls are not queued for
that thread.
Handle part contacts
Touched passes the contacting part. For a character body part, check its parent
for a Humanoid. The presence of a humanoid identifies a character, which may be
a player character or an NPC.
Multiple body parts and repeated physics contacts can trigger separate callbacks. For damage or rewards, track cooldowns per character or use an explicit one-time guard.
TouchEnded reports individual part contacts ending. It does not establish that
an entire character has left the area. See
BasePart.GetTouchingParts for query
behavior. Use workspace overlap queries when the operation requires spatial
overlap rather than recorded physics contacts.
Watch a property
Changed passes the changed property name. Filter this name before reading a
specific property.
workspace.Changed:Connect(function(property)
if property == "Gravity" then
print(workspace.Gravity)
end
end)Callback errors
An error stops that callback invocation and is reported in output. The connection
remains active for later events. Handle expected failures with pcall and report
or recover from the error.