Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why would 'if [this] == nil then' give me an error?

i made an if statement and "lalalaa" is not in workspace, so i'm pretty sure this would work but it always gives me an error.

if game.Workspace.lalalaa == nil then
print 'Hello world!'
end

Error: 15:53:37.546 - lalalaa is not a valid member of Workspace 15:53:37.546 - Script 'Workspace.Script', Line 1 15:53:37.547 - Stack End

2 comments

0

Please include the error.

0

added error @CreativeEnergy

2 answers

✓ Accepted answer

You're trying to reference an object that doesn't exist, so it'll throw the error before it even gets to the "== nil" part. To solve this, you can simply do:

if not game.Workspace:FindFirstChild("lalalaa") then
print('hello world')
end

1 comment

0

This helped me out, thanks. This is how I can show my gratitude because I cannot upvote your answer.

This is an order-of-operations issue.

In order to evaluate game.Workspace.lalalaa == nil, you need to evaluate both the left and the right first.

nil is fine to evaluate.

But what is game.Workspace.lalalaa? Trying to access something that doesn't exist in the Workspace will cause an error.

Thus it never even gets to the point where it can compare it to nil.


Instead of using indexing on ROBLOX objects to see if children exist, use :FindFirstChild( name ) which will just return nil and make the above work:

if workspace:FindFirstChild("lalalaa") == nil then
	-- It doesn't exit
else
	-- It does exit
end

Note that checks like == nil usually are more wordy than necessary. You could just say not workspace:FindFirstChild("lalalaa") because not nil will be true and not lalalaa (where lalalaa is the object) will be false.

This discussion is preserved as it was. New answers, comments, and votes are closed.