Infinite loop while using Event as test in while loop

I have this piece of code

while hammer.Unequipped do

wait()
print("Hammer is unequipped")

end

The loop is not ending when the hammer is equipped. Why does this happen?

Tool.Unequipped is an event that is always in a Tool instance. While loops pass if the statement isn’t falsey or nil. Try using a boolean to signify if the tool is equipped or unequipped.

1 Like

Unequipped is an event, so it will always be truthy. (its a userdata, and only false and nil are falsy)
If you want to check if it is unequipped, using both Equipped and Unequipped should work.

local IsEquipped = false
hammer.Equipped:Connect(function()
    IsEquipped = true
end)
hammer.Unequipped:Connect(function()
    IsEquipped = false
end)
while not IsEquipped do
    wait()
    print("Hammer is unequipped")
end

Depending on what you’re doing, this could be done differently. For example, if this is a player’s tool, you could simply check if the tool was a descendant of the player’s character.

2 Likes