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?
What is the difference between 'if string then end' and 'if string ~= nil then end'?
2 answers
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
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
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
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. :)