LUA / CHAPTER 01
Values, types, and truth
BeginnerReason about Lua values without borrowing another language’s truth rules.
By the end of this chapter
- Recognize nil as absence
- Predict boolean conditions
- Distinguish arithmetic from concatenation
The idea
Lua values carry types, while a variable can refer to values of different types over its lifetime. Common types include nil, boolean, number, string, table, and function. A variable without an assigned value has nil. Use local declarations for ordinary working variables so their names remain within the intended scope. Numbers support arithmetic, and the concatenation operator .. joins strings into a result.
Only false and nil are false in a condition. Zero and the empty string are both true, which matters when translating an algorithm from another language. The operators and and or return selected operands rather than converting every result to a boolean. A fallback using or therefore replaces false as well as nil; use an explicit nil check when false is meaningful input.
local count = 0
local label = ""
if count then print("zero is true") end
if label then print("empty is true") end
print("Items: " .. (3 + 2))zero is true empty is true Items: 5
Both conditions succeed because their values are neither false nor nil. Parentheses make the arithmetic happen before the result is concatenated.
Try it yourself
Write a function that substitutes ten only when its argument is nil, preserving zero and false.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING