Back to Blog

Learn Lua in Neovim: If Statements — if, elseif, else & Grade Calculator | Episode 7

Sandy LaneSandy Lane

Video: Learn Lua in Neovim: If Statements — if, elseif, else & Grade Calculator | Episode 7 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Lua in Neovim: If Statements — if, elseif, else & Grade Calculator

In this tutorial, you'll learn how to control the flow of your Lua programs using conditional statements. We build a simple grade calculator that assigns letter grades based on a numeric score, demonstrating how to use if, elseif, and else branches effectively.

Code

-- Define a numeric score
local score = 85

-- Check the score and assign a grade
if score >= 90 then
  print("Grade A")
elseif score >= 80 then
  print("Grade B")
elseif score >= 70 then
  print("Grade C")
elseif score >= 60 then
  print("Grade D")
else
  print("Grade F")
end

Key Points

  • The if condition then ... end structure runs code only when the condition is true.
  • The else block acts as a fallback when no previous conditions are met.
  • elseif allows checking multiple conditions sequentially in order.
  • Lua executes only the first true branch and skips the rest, making order important.
  • Using Neovim’s cw command lets you quickly change values like the score to test different branches.