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

What is the difference between 'if string then end' and 'if string ~= nil then end'? [closed]

Asked by 10 years ago

I have seen these two pieces of coding in allot of script, I mostly see if string ~= nil then end more than if string then end, but I don't get whats the difference between the two, nor why people use ~= nil in the code aswell?

Locked by TheeDeathCaster and Goulstem

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

2 answers

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

If str is only either a string or nil, there is no difference between the two conditions.


Condition for if and while check whether or not values are truthy or falsy.

There are only two falsy values: nil and false.

All other values are truthy -- strings (including empty string), numbers (including 0 and negatives), tables (including empty table), objects (including objects not parented), true, coroutines, functions, etc -- everything.


If something is either something except false, or nil, then the following are equivalent

if something then
--
if something ~= nil then

since something ~= nil reflect the truthy states that something has.


The more general form is

if something ~= nil and something ~= false then

though usually it is clear whether or not something will be equal to false (usually not, so that can be dropped)


Many people would use ~= nil because it's more explicit in what it checks, and because it is also explicitly forms a boolean for the condition, rather than some other type (like a string).

In my opinion, it is better to go without the ~= nil because

  • code is shorter
  • code is clearer intuitively
0
Wow, Thanks man! That explains allot and fully answers my question! I was worried I was scripting wrong by not using '~= nil'. :P I am so greatful man, thank you. :) TheeDeathCaster 2368 — 10y
Ad
Log in to vote
-1
Answered by
IcyEvil 260 Moderation Voter
10 years ago

if string ~= nil then end

Says, If a string Does not Equal Nil(Nothing) then end

if string then end

Seems to say, If it is a String then end

Seems the same to me, But im not an Expert lua'er