Back to Blog

Learn Lua in Neovim: Math & String Libraries — floor, random, sub, format & Dice Roller | Episode 23

Sandy LaneSandy Lane

Video: Learn Lua in Neovim: Math & String Libraries — floor, random, sub, format & Dice Roller | Episode 23 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Lua in Neovim: Math & String Libraries — floor, random, sub, format & Dice Roller

Lua's built-in math and string libraries provide essential functions for numerical calculations and text manipulation. This guide explores key math functions like floor, ceil, abs, and random, alongside string operations such as substring extraction, pattern searching, and formatted output. Finally, we'll combine these tools to build a simple dice roller function to simulate rolling dice with customizable count and sides.

Code

-- Math library examples
print(math.floor(3.7))    -- rounds down to 3
print(math.ceil(3.1))     -- rounds up to 4
print(math.abs(-5))       -- absolute value: 5
print(math.max(10, 20))   -- maximum: 20
print(math.min(10, 20))   -- minimum: 10
print(math.pi)            -- constant π ≈ 3.14159

-- Calculate area of a circle with radius 5
local radius = 5
local area = math.pi * radius * radius
print(string.format("Area of circle: %.2f", area))

-- Random numbers: seed and generate
math.randomseed(os.time())  -- seed random generator
print(math.random(1, 6))    -- random integer between 1 and 6

-- String library examples
local s = "Hello, Neovim!"

print(string.sub(s, 1, 5))       -- substring "Hello"
print(string.find(s, "Neo"))     -- find "Neo" returns start and end indices
print(string.format("Number: %d, Hex: %x", 255, 255)) -- formatted output

print(string.byte("A"))          -- ASCII code of 'A' = 65
print(string.char(66))           -- character for ASCII 66 = 'B'

-- Dice roller function: roll 'count' dice with 'sides'
function roll_dice(count, sides)
  local total = 0
  for i = 1, count do
    total = total + math.random(1, sides)
  end
  return total
end

print("Roll 3d6:", roll_dice(3, 6))  -- roll three 6-sided dice

Key Points

  • math.floor and math.ceil round numbers down and up, respectively.
  • math.randomseed initializes the random number generator for varied results.
  • string.sub extracts substrings by specifying start and end indices.
  • string.format allows formatted strings similar to printf in C.
  • Combining math.random and string functions enables practical utilities like a dice roller.