Check if character is an NPC?

So I have this script that is supposed to arrest a player, but when checking if the characters parent is called “NPCs” it does not work, any help?

distance = 5
local player = game.Players.LocalPlayer

script.Parent.Equipped:connect(function(mouse)
	mouse.Button1Down:Connect(function()
		if mouse.Target.Parent:FindFirstChild("Humanoid") and (mouse.Target.Position - script.Parent.Handle.Position).magnitude <distance then
		local Prisoner = mouse.Target.Parent
		if not Prisoner.Parent.Name == "NPCs" then
		local ArrestedIdle = Prisoner.Humanoid:LoadAnimation(script.Parent.ArrestedIdle)
		ArrestedIdle:Play()
        script.Parent.GiveGui:FireServer(Prisoner)
end
		end
		end)
	end

Oh I used to make this mistake all the time.

The problem occurs at this line not Prisoner.Parent.Name == "NPCs"

I assume you want it to check whether the not of Prisoner.Parent.Name == "NPCs is true. However what the lua compiler is actually doing is comparing the not of Prisoner.Parent.Name to NPCs and then that to true.

Here is an example
image

Notice the pair of parentheses around the second if then statement and how it outputted Not NPCs!?
This is because the parentheses will “prioritize” the evaluation of whatever is inside first.

With this you may be wondering “Why is the code not throwing an error, you can’t get the not of a string value it makes no sense!”

Well it actually does make sense. All datatypes have a concept called “truthiness” which in short you could define as meaning “they just exist”. This is why things like if "a" then and while wait() do work.

Since all datatypes have “truthiness” it means they are essentially true. Therefore not AnyDataType would be false. (EXCLUDING A BOOLEAN OF VALUE "false" AND ANY VALUE "nil")

image

Think of it like a math problem. There is an obvious difference between 5 * 2 + 3 and 5 * (2 + 3). In the first example 5 * 2 + 3 evaluates to 10 + 3 to 13. In the second 5 * (2 + 3) evaluates to 5 * 5 which is 25

I find it best (and sometimes messy) to remove all ambiguity by encapsulating all of my multi operand expressions in parentheses.

Example: local x = a + b < c and d or elocal = ((a + b) < c) and d) or e

TL;DR: Use if not (Prisoner.Parent.Name == "NPCs") then

https://www.luafaq.org/gotchas.html
http://lua-users.org/wiki/ExpressionsTutorial

6 Likes