Back to Blog

Learn Lua in Neovim: Booleans, Nil & Comparisons — The Truthy Gotcha | Episode 5

Sandy LaneSandy Lane

Video: Learn Lua in Neovim: Booleans, Nil & Comparisons — The Truthy Gotcha | Episode 5 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Lua in Neovim: Booleans, Nil & Comparisons — The Truthy Gotcha

In this lesson, we explore Lua's boolean and nil types along with its six comparison operators. You'll learn why only false and nil are falsy in Lua, and discover the common beginner trap that 0 and empty strings are actually truthy values in Lua, unlike many other programming languages.

Code

-- Lua boolean literals
local is_active = true
local is_done = false

-- nil represents absence of a value
local no_value = nil

-- Comparison operators
local a = 5
local b = 10

print(a < b)    -- true: less than
print(a >= b)   -- false: greater than or equal
print(a == b)     -- false: equality
print(a ~= b)     -- true: not equal (note ~=, not !=)

-- Truthy and falsy values in Lua
if 0 then
  print("0 is truthy")  -- prints because 0 is truthy in Lua
end

if "" then
  print("Empty string is truthy")  -- prints because "" is truthy
end

if false then
  print("This won't print")
end

if nil then
  print("Nor will this")
end

Key Points

  • true and false are the only boolean literals in Lua.
  • nil represents the absence of any value or an uninitialized variable.
  • ~= is Lua's not-equal operator, unlike the != used in many other languages.
  • Only false and nil evaluate as falsy; everything else is truthy.
  • 0 and empty strings ("") are truthy in Lua, a common source of confusion for beginners.