Truthy and Falsy Values
Part of the Fundamentals section of Coddy's Lua journey — lesson 24 of 90.
When using logical operators like and, or, and not, Lua needs to determine what counts as "true" or "false" in logical contexts. This concept is called truthy and falsy values, and Lua handles it differently from many other programming languages.
In Lua, only two values are considered falsy (treated as false in logical operations):
print(false and "This won't print") -- false is falsy
print(nil and "This won't print") -- nil is falsyEverything else in Lua is considered truthy (treated as true in logical operations). This includes values that might surprise you if you're coming from other languages:
print(0 and "This will print") -- 0 is truthy in Lua!
print("" and "This will print") -- Empty string is truthy!
print({} and "This will print") -- Empty table is truthy!Cheat sheet
In Lua, only two values are considered falsy (treated as false in logical operations):
falsenil
Everything else is truthy, including:
0(unlike many other languages)- Empty strings
"" - Empty tables
{}
print(false and "Won't print") -- false is falsy
print(nil and "Won't print") -- nil is falsy
print(0 and "Will print") -- 0 is truthy in Lua
print("" and "Will print") -- Empty string is truthyTry it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators 2 Relational & Logic
Equality OperatorsRelational OperatorsThe 'and' OperatorThe 'or' OperatorThe 'not' OperatorShort-Circuit EvaluationTruthy and Falsy ValuesRecap - Simple Logic7Basic Conditional Logic
The if-then StatementThe if-then-else StatementThe elseif StatementRecap - Treasure Chest2Variables and Data Types
What is a Variable?NumbersStringsBooleansThe Value 'nil'The type() FunctionNaming ConventionsRecap - Character Profile5Basic Output
Printing LiteralsPrinting VariablesPrinting Multiple ValuesCombining Strings & VariablesThe tostring() FunctionInputCastRecap - Status ReportRecap - Till 1208String Manipulation Basics
string.len()string.upper & string.lowerstring.sub()string.rep()string.find()Recap - Format Username3Operators 1 Arithmetic & Conc
Arithmetic OperatorsModulo OperatorExponentiation OperatorString ConcatenationOperator PrecedenceRecap - Simple Calculations6Project: Character Stats Disp
Welcome MessageDeclare Character Stats9Functions Basics
Declaring a FunctionCalling a FunctionFunctions with ParametersFunctions with Multiple ParamsThe 'return' StatementRecap - Area Calculator