Difference between revisions of "Lua: Booleans"
From Mario Fan Games Galaxy Wiki
(Created page with '{{Lua}} Up until Lua 5.0, Lua did not have an explicit '''boolean''' type; instead, boolean operations were performed using <tt>nil</tt> as <tt>false</tt> and any other n…') |
|||
Line 1: | Line 1: | ||
{{Lua}} | {{Lua}} | ||
− | Up until [[Lua]] 5.0, Lua did not have an explicit '''boolean''' type; instead, [[boolean]] operations were performed using <tt>nil</tt> as <tt>false</tt> and any other non-<tt>nil</tt> datatype as <tt>true</tt>. Lua 5.0 introduced <tt>true</tt> and <tt>false</tt> as a true and separate boolean type. | + | Up until [[Lua]] 5.0, Lua did not have an explicit '''boolean''' type; instead, [[boolean]] operations were performed using <tt>nil</tt> as <tt>false</tt> and any other non-<tt>nil</tt> datatype as <tt>true</tt>. Lua 5.0 introduced <tt>true</tt> and <tt>false</tt> as a true and separate boolean type. When [[Lua: Coercion|coercion]] is allowed, non-boolean values will be coerced: <tt>nil</tt> is seen as <tt>false</tt>, anything else as <tt>true</tt>. Only the ''result'' of a boolean expression is the returned boolean value. |
− | + | This is important to remember, as this case shows: | |
+ | <source lang="lua" enclose="div">test = 1 | ||
+ | |||
+ | if test then | ||
+ | print("evaluated true") --> this is printed | ||
+ | else | ||
+ | print ("evaluated false") | ||
+ | end | ||
+ | |||
+ | if test == true then | ||
+ | print("evaluated true") | ||
+ | else | ||
+ | print ("evaluated false") --> this is printed | ||
+ | end</source> | ||
+ | If you check the [[Lua: Coercion|coercion]] notes, you will see Lua does not automatically coerce values used in boolean comparisons; therefore, the second <tt>if</tt> statement will evaluate to <tt>false</tt>. However, the first will evaluate to <tt>true</tt>, because coercion is allowed in this case. |
Latest revision as of 22:55, 14 November 2009
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
Up until Lua 5.0, Lua did not have an explicit boolean type; instead, boolean operations were performed using nil as false and any other non-nil datatype as true. Lua 5.0 introduced true and false as a true and separate boolean type. When coercion is allowed, non-boolean values will be coerced: nil is seen as false, anything else as true. Only the result of a boolean expression is the returned boolean value.
This is important to remember, as this case shows:
test = 1
if test then
print("evaluated true") --> this is printed
else
print ("evaluated false")
end
if test == true then
print("evaluated true")
else
print ("evaluated false") --> this is printed
end
If you check the coercion notes, you will see Lua does not automatically coerce values used in boolean comparisons; therefore, the second if statement will evaluate to false. However, the first will evaluate to true, because coercion is allowed in this case.