Lua: Booleans

From Mario Fan Games Galaxy Wiki
Lua
Lua.gif
Basics
Intermediate
Advanced
XLua
Add to this template
 Standardwikimessagebox.png This article assumes the use of Lua 5.1.

Information may not be accurate or may need revision if you are using a different version.

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.