I'm having trouble understanding how the expressions ""==true
and ""==false
both evaluate to false
.
Trying the following in the lua interpreter and ilua result in the same output:
> =""==true
false
> =""==false
false
Or executing the following:
print(""==true)
print(""==false)
print(""==nil)
Outputs
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
false
false
false
>
Another example:
> =""~=true
true
> =""==false
false
When the following code is run:
if "" then -- if ""==true
print "was true"
end
if not "" then -- if ""==false
print "was not true"
end
The output is (seemingly inconsistently)
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
was true
>
As expected per the Lua FAQ which states
C-like languages regard 0 as equivalent to false, but this is not true for Lua. Only an explicit false or nil are equivalent to false. When in doubt, make the condition explicit, e.g. if val == nil then ... end unless the value is actually boolean.
How can a value be not equal to true
,false
or nill
?
The operator == tests for equality; the operator ~= is the negation of equality. We can apply both operators to any two values. If the values have different types, Lua considers them different values. Otherwise, Lua compares them according to their types.
The boolean type has two values, false and true, which represent the traditional boolean values. However, they do not hold a monopoly of condition values: In Lua, any value may represent a condition. Conditionals (such as the ones in control structures) consider false and nil as false and anything else as true.
In lua '==' for string will return true if contents of the strings are equal. As it was pointed out in the comments, lua strings are interned, which means that any two strings that have the same value are actually the same string.
In lua, all values are true, except nil and false.
The type of ""
is string, not boolean, so it's not equal to either true
or false
.
To be more general, when Lua compares two values, it tests their type first, if the type mismatch, Lua thinks the two values as not equal immediately.
When used as control expression, the only false values in Lua are false
and nil
, everything else is evaluated as true value. Some popular confusions include the number 0
, the empty string ""
, the string "0"
, they are all true values. Note again that false
and nil
are not equal because they are different types.
So back to the example, in the code
if "" then -- if ""==true
print "was true"
end
Lua tests if ""
is false
or nil
, since it's neither, then Lua treats the condition as true value.
All Lua values when used as Booleans evaluate to true, except nil and false. This does not mean that values that evaluate to true are equal to true. If you want to convert a value v
to Boolean, use not not v
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With