Back to Blog

Lua with Neovim: Type Conversion — Automatic Coercion, Safe Defaults & Explicit Casts | Episode 28

Sandy LaneSandy Lane

Video: Lua with Neovim: Type Conversion — Automatic Coercion, Safe Defaults & Explicit Casts | Episode 28 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Lua with Neovim: Type Conversion — Automatic Coercion, Safe Defaults & Explicit Casts

Lua is dynamically typed and sometimes converts types automatically, but this behavior can be subtle and inconsistent. In this guide, we explore explicit conversions using tonumber and tostring, how automatic coercion works in arithmetic but not in comparisons, and how to handle conversion failures safely with default values and formatted output.

Code

-- Automatic coercion in arithmetic works when strings represent numbers
local result = "10" + 5  -- Lua converts "10" to number 10 automatically
print(result)            -- Output: 15

-- But coercion fails in comparisons
print("10" > 5)        -- Error: attempt to compare string with number

-- Explicit conversion with tonumber returns a number or nil
local num1 = tonumber("123")     -- 123 (number)
local num2 = tonumber("abc")     -- nil (conversion fails)

-- Safe default pattern to avoid nil
local safe_num = tonumber("abc") or 0
print(safe_num)                  -- Output: 0

-- tostring converts any value to a string
local str = tostring(456)        -- "456"
print(str)

-- Using string.format for formatted output
local pi = 3.14159
print(string.format("Pi to 2 decimals: %.2f", pi))  -- Output: Pi to 2 decimals: 3.14

Key Points

  • tonumber(value) converts strings to numbers safely, returning nil if conversion fails.
  • tostring(value) converts any Lua value to its string representation.
  • Lua automatically coerces strings to numbers in arithmetic operations but not in comparisons.
  • Use the safe default pattern (tonumber(value) or 0) to handle invalid numeric input gracefully.
  • string.format provides precise control over number and string output formatting.