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