Back to Blog

Learn Lua in Neovim: Numbers and Arithmetic — Operators & Receipt Calculator | Episode 3

Sandy LaneSandy Lane

Video: Learn Lua in Neovim: Numbers and Arithmetic — Operators & Receipt Calculator | Episode 3 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Lua in Neovim: Numbers and Arithmetic — Operators & Receipt Calculator

In this lesson, we explore Lua's single number type and its full set of arithmetic operators, including addition, subtraction, multiplication, division, modulo, exponentiation, and floor division. To demonstrate these concepts, we build a simple receipt calculator that computes subtotals, tax, and totals using real-world math.

Code

-- Define item prices
local item1 = 12.50
local item2 = 7.30
local item3 = 4.20

-- Calculate subtotal by adding item prices
local subtotal = item1 + item2 + item3

-- Define tax rate (e.g., 8%)
local tax_rate = 0.08

-- Calculate tax amount by multiplying subtotal by tax rate
local tax = subtotal * tax_rate

-- Calculate total by adding subtotal and tax
local total = subtotal + tax

-- Demonstrate floor division: total divided by 5, rounded down
local floor_div = total // 5

-- Calculate remainder when total is divided by 5
local remainder = total % 5

-- Calculate total squared using exponentiation
local total_squared = total ^ 2

-- Print all results
print("Subtotal: $" .. subtotal)
print("Tax: $" .. tax)
print("Total: $" .. total)
print("Floor division of total by 5: " .. floor_div)
print("Remainder of total divided by 5: " .. remainder)
print("Total squared: " .. total_squared)

Key Points

  • Lua uses a single number type for all numeric operations, simplifying math handling.
  • The // operator performs floor division, returning the integer quotient rounded down.
  • The % operator computes the remainder after division, useful for modular arithmetic.
  • The ^ operator raises a number to a specified power, enabling exponentiation.
  • Using variables to store intermediate results keeps calculations clear and organized.