Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by
DanzLua 2879 Moderation Voter Community Moderator
9 years ago

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

0
Please include the error. AmericanStripes 610 — 9y
0
added error @CreativeEnergy DanzLua 2879 — 9y

2 answers

Log in to vote
1
Answered by 9 years ago

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
0
This helped me out, thanks. This is how I can show my gratitude because I cannot upvote your answer. jonathanpecany100 0 — 4y
Ad
Log in to vote
4
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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.

Answer this question