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
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
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
.