How to check if something exists without multiple indentations?

Hey so I was curious if Roblox ever decided to properly implement a way to check if something “exists” or hasn’t been destroyed/ added to debris.

Normally you’d just do:

if object ~= nil then

But that doesn’t seem to work a lot of the time. You’ll get an error immediately after if you try to reference a property or call FindFirstChild() on it.

So you have to do:

if object ~= nil then
      if object.Parent~= nil then

I was curious if there’s a better way to do this, because my scripts spit out loads of errors any time something is deleted or missing. (Like if you jumped off the edge with a tool, the tool will chuck out errors trying to reference nil objects even though there exists 1 layer sanity checks)

Well you don’t need to do if object ~= nil you just need to do if object then. And whats wrong its only a couple extra words to write

You could do:

if not object then

It checks if the object is not nil.

Actually that checks if the object does not exist since not is making it opposite and thus saying check if it is the opposite of existing.

@VeinTweek’s suggestion is most used. You can use if object then to check if the object exists.

Does that work now? I remember that being the outright incorrect way to do it for the longest time because of it returning false positives endlessly

You can do:

if object and object.Parent then

If the first statement is false then it won’t move on to the second statement.

EDIT: I replied to wrong person, sorry! Your method works

I just conducted some tests and just doing a “if [variable] then” approach doesn’t work

    if target ~= nil then
		if target.Parent ~= nil then
			if target.Parent.Parent ~= nil then
			else
				target = nil
			end
		else
			target = nil
		end
	end

This is some code I run on the value of an ObjectValue. It’s checking if target (a humanoidrootpart in a player) exists. When I reset, THIS version of the code is able to verify that indeed it is gone.

    if target then
	else
		target = nil
	end

THIS, however, doesn’t work. Even after the player dies it will still have a target value that lingers. It still believes the humanoidrootpart exists.