Codectionary / Developer documentation / Luau

Events, connections and cleanup

Connect registers a callback and returns a connection you can disconnect. The callback runs when the event fires, not when it is registered. Long-lived services can keep callbacks alive after a feature has ended, so give each connection a clear cleanup point.

Syntax

local connection = signal:Connect(function()
    print("Changed")
end)
connection:Disconnect()

Examples

Watch one property

Script in ServerScriptService. This self-contained example watches a part’s color, changes it and disconnects before destroying the part. The callback reads the new property value.

local part = Instance.new("Part")
part.Anchored = true
part.Parent = workspace
local connection = part:GetPropertyChangedSignal("Color"):Connect(function()
    print("Color:", part.Color)
end)
part.Color = Color3.fromRGB(200, 90, 50)
task.delay(2, function()
    connection:Disconnect()
    part:Destroy()
end)

Stop listening to a long-lived service

LocalScript in StarterPlayerScripts. This counts five seconds of client frames, then disconnects. A service such as RunService outlives a temporary UI or character feature.

local RunService = game:GetService("RunService")
local elapsed = 0
local connection: RBXScriptConnection?
connection = RunService.Heartbeat:Connect(function(dt)
    elapsed += dt
    if elapsed >= 5 then
        if connection then connection:Disconnect() end
        print("Finished watching")
    end
end)

Best practices

  • Store connections when you need to stop callbacks before their signal owner is destroyed.
  • Connect a function rather than calling it inside Connect.
  • Do not install the same listener every frame or on every button press; repeated connections multiply actions.

At a glance

Purpose
Typed scripting and Roblox development
File extension
.luau
Runs in
Luau host; Roblox engine examples require Roblox Studio
Usually used with
Roblox APIs and Studio

Specifications & further reading

Related Luau documentation