Purpose of '~= nil'

Hello everyone!

I was wondering what the purpose is of ‘~= nil’.

For example, I came across a teleportation script:

script.Parent.Touched:Connect(function(hit)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	
	if humanoid ~= nil then 
		hit.Parent.HumanoidRootPart.CFrame = CFrame.new(workspace.TeleportParts["BluePart"].Position) + Vector3.new(0,3,0)
	end
end)

Why is ‘~= nil’ being used here? Because I could just write:

if humanoid then

Thnx in advance!

if X ~= nil will return true if the value exists, even if it’s false. if X will return if the value exists and it is not false.

2 Likes

There is no difference in this situation between

if humanoid ~= nil then

and

if humanoid then

The difference comes when you might want to compare false, and nil.
Example:

You have a data request, which is boolean, for example, if a user is banned on your game.

If you did

if not PlayerIsBanned then

This would be valid when:

  • There is no ban value set; and
  • When the user is not banned

whilst if you did

if PlayerIsBanned == false then

This would work only when the player is definitely not banned.

10 Likes

The true purpose of ~= nil is the usage of cases when false should be used. Because when you reference something such as GuiObject.Enabled, it will return false if it’s not visible.

Thus avoiding the issue, it can be done like this: Extracted from previous script testing session.

if not properties then
	if ui.Visible ~= nil then
		ui.Visible = not ui.Visible
	elseif ui.Enabled ~= nil then
		ui.Enabled = not ui.Enabled
	end
else
	for property, value in next, properties do
		if ui[property] ~= nil then
			ui[property] = value
		end
	end
end

The ui demonstrates any kind of Instance.

2 Likes

So if I understand it correctly, it can also function as a safety system. As in being 100% sure something is going to happen.

(I might be completely wrong)

It avoids bumping into unnecessary errors or system failing such as when you’re trying to find out if the object has Enabled property.

In other words, yes. It makes sure it exists.

3 Likes