Learn Lua in Neovim: Logical Operators — and, or, not & Ternary Idiom | Episode 8
Video: Learn Lua in Neovim: Logical Operators — and, or, not & Ternary Idiom | Episode 8 by Taught by Celeste AI - AI Coding Coach
Watch full page →Learn Lua Logical Operators: and, or, not & Ternary Idiom
Logical operators in Lua let you combine and manipulate boolean conditions effectively. In this example, we create a theme park ride eligibility checker using and, or, and not operators, plus the common Lua ternary idiom for inline conditional values.
Code
-- Define rider's age and height
local age = 12
local height = 140 -- in centimeters
-- Check if rider meets minimum age and height requirements
local can_ride = (age >= 10) and (height >= 130)
if can_ride then
print("You can ride!")
else
print("Sorry, not allowed.")
end
-- Using 'or' to allow entry if either condition is true
local has_ticket = false
local is_vip = true
if has_ticket or is_vip then
print("Welcome to the park!")
else
print("Please buy a ticket.")
end
-- Using 'not' to invert a boolean
local park_closed = false
if not park_closed then
print("The park is open!")
else
print("The park is closed.")
end
-- Ternary idiom: choose a message based on pass/fail
local score = 75
local result = (score >= 60) and "Pass" or "Fail"
print("Result:", result)
Key Points
andreturns true only if both conditions are true.orreturns true if at least one condition is true.notinverts a boolean value, turning true to false and vice versa.- The Lua ternary idiom
x and a or bselectsaifxis true, otherwiseb. - Logical operators enable concise, readable condition checks in Lua scripts.