Looking at the "top level", there are essentially two statements:
function onTouched(hit)
...
end
script.Parent.Touched:connect(onTouched)
A function declaration (that uses the function keyword) that defines a function called onTouched with one parameter named hit.
Second, a call to connect to the Touched event.
Events trigger on some particular stimulus, calling any function that has been passed to their connect method. In this case, onTouched, the function defined before, is passed.
onTouched will now be called whenever another part touches script.Parent. According to the Wiki article on Touched, it passes one parameter -- the other part that touched script.Parent.
Returning to the function:
function onTouched(hit)
local d = hit.Parent:GetChildren()
for i=1, #d do
if (d[i].className == "Hat") then
d[i]:remove()
end
end
end
hit is the parameter of the other object touching script.Parent. If it's a player, it will be a Leg or Arm, Head, Torso, or perhaps the handle (the Part inside) of a Hat or Tool.
local marks the definition of a new variable, d. d is the list of the children of hit's parent.
Imagine that hit was the player's Leg. Then hit.Parent is the parent of their leg -- the Character model.
Asking for the Children of the character model would give the player's equipped Tools, Hats, and their limbs, Torso, and Head.
We loop through this list, from starting at 1 up to #d, where #d is the number of things in the list d (the number of things in hit.Parent)
d[i] is then the ith object in the list.
We check if the className, the "type" of the object, is a Hat, and in that case, remove (destroy) it.
The function could be improved much, though:
function onTouched(hit)
local model = hit.Parent
if model then
for _, child in pairs(model:GetChildren()) do
if child:IsA("Hat") then
child:Destroy()
end
end
end
end
1 comment
Dang, thanks so much.