33. Events and connections — Homework solutions
Roblox snippets — paste into a Script in Studio to try
them. The .lua files are in
exercises/33/homework/solutions/.
Problem 1 — Touched printer
Worked solution.
part.Touched:Connect(function(otherPart)
print(otherPart.Name .. " touched it")
end):Connect registers the function; it runs each time
something touches the Part, passing the touching Part as
otherPart.
Problem 2 — Greet on join
Worked solution.
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
print("Welcome, " .. player.Name .. "!")
end)PlayerAdded fires once per joining player, giving you
the player.
Problem 3 — Add a debounce
Worked solution.
local collected = false
part.Touched:Connect(function(otherPart)
if collected then return end
collected = true
print("bang!")
end)The early return skips every touch after the first, so
bang! prints once.
Common mistakes.
- Declaring
collectedinside the connected function. It would reset tofalseon every touch and block nothing. The flag must live outside, so it persists between touches.
Challenge — Player-only touch
Worked solution.
local Players = game:GetService("Players")
part.Touched:Connect(function(otherPart)
local character = otherPart.Parent
local player = Players:GetPlayerFromCharacter(character)
if player then
print(player.Name .. " scored")
end
end)GetPlayerFromCharacter returns nil for
anything not part of a player's character, so the if player
guard ignores stray bricks and reacts only to players.
Done?
Your code can react to the world — touches, joins, and more — with
debounces to keep it sane. Next, Services and the data
model maps the big containers your scripts reach into:
Workspace, Players, the rest.