Back to Blog

Learn Lua in Neovim: Multiple Returns and Variadics — return a, b and ... | Episode 13

Sandy LaneSandy Lane

Video: Learn Lua in Neovim: Multiple Returns and Variadics — return a, b and ... | Episode 13 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Lua in Neovim: Multiple Returns and Variadics — return a, b and ... | Episode 13

Lua functions can return multiple values simultaneously and accept a variable number of arguments, making them very flexible. This episode demonstrates how to return and capture multiple values, discard unwanted ones using the underscore convention, and create variadic functions with ... and select() to handle any number of inputs.

Code

-- Function returning multiple values: minimum and maximum of two numbers
local function min_max(a, b)
  if a < b then
    return a, b
  else
    return b, a
  end
end

-- Capture both return values
local min, max = min_max(10, 5)
print("Min:", min, "Max:", max)  -- Output: Min: 5 Max: 10

-- Function returning quotient and remainder
local function divide(dividend, divisor)
  local quotient = math.floor(dividend / divisor)
  local remainder = dividend % divisor
  return quotient, remainder
end

-- Capture only quotient, discard remainder using _
local q, _ = divide(17, 4)
print("Quotient:", q)  -- Output: Quotient: 4

-- Variadic function to sum any number of arguments
local function sum(...)
  local total = 0
  -- Count how many arguments were passed
  local n = select("#", ...)
  -- Iterate over all arguments by index
  for i = 1, n do
    total = total + select(i, ...)
  end
  return total
end

print("Sum:", sum(1, 2, 3, 4, 5))  -- Output: Sum: 15
print("Sum:", sum(10, 20))         -- Output: Sum: 30

Key Points

  • Lua functions can return multiple values by separating them with commas in the return statement.
  • Multiple return values can be captured simultaneously with comma-separated variables.
  • The underscore (_) is a convention to discard unwanted return values when capturing.
  • The ... syntax allows functions to accept any number of arguments (variadic functions).
  • select("#", ...) returns the count of variadic arguments, enabling iteration over them.