Which one is better to use == not nil or ~= nil

Variable == not nil
or
Variable ~= nil

i want to know which one have a better efficiency in lua, i know that is not a big difference, but if there is a difference in what the processor have to do, i want to know.

3 Likes

If you are using this in an if statement, you can do if Variable then because nil is a false value.

I would say Variable ~= nil is better for readability.

Both of these are inefficient because of using extra characters, just do:

if variable then

end

If the variable had a value, then it will be like a true-ish value.

2 Likes

To answer your question directly (and this might not be the easiest to understand) ‘not nil’ is the same thing as ‘true’, so you could rewrite the code as
if thing == true
which would fail on anything that isn’t exactly ‘true’
game.Workspace is not nil, but it’s also not true. So that wouldn’t even work at all.
The second way you list works, but listen to the other posters.

yea , there is also this option, but if you are checking if a bool value exist and you do a
if Variable then
there is no difference between a false bool value and a nil value

Correct, but if you’re using a boolean then if not variable then will work for both nil and false

1 Like

Are you checking if the Instance exists or its value?

i want to know which one is faster, if its
Variable == not nil
or
Variable ~= nil

to check if a boolean exist

Theoretically speaking they don’t make a difference, but I believe ~= would be faster because there are less things to consider.

3 Likes

Honestly the difference between the two in terms of speed is unnoticeable. We talking about something that is a few milliseconds, so unless you’re dealing with satellites I wouldn’t worry too much about it.

yea, i know that there is almost no difference, but i want to have a pattern when checking if a Boolean exist, and i want a reason for choosing one of them, and i think i am going with “~=” considering what everybody is saying

if variable then

= “If variable is anything except false or nil”

if variable ~= nil then

= “If variable is not nil”


And of course, you can always test these things out by yourself in studio with the command bar.

1 Like