LuLua · Lesson 4 of 8

Functions

Functions in Lua are values — store them in tables, pass them around, return several results at once. This flexibility is why Lua works so well as a scripting layer.

Lua
local function greet(name)
  return "Hello, " .. name .. "!"
end
print(greet("Ada"))

-- Multiple return values — very Lua:
local function divide(a, b)
  if b == 0 then
    return nil, "division by zero"   -- value, error pattern
  end
  return a / b
end

local result, err = divide(10, 0)
if not result then
  print("Error: " .. err)
end

-- Missing arguments are nil; extra ones are dropped:
local function hello(name)
  name = name or "stranger"      -- idiomatic default
  print("Hi, " .. name)
end
hello()          -- Hi, stranger
Lua
-- Functions are values:
local shout = function (s) return s:upper() .. "!" end

local ops = {
  add = function (a, b) return a + b end,
  mul = function (a, b) return a * b end,
}
print(ops.add(2, 3))     -- 5

-- Closures — functions remember their surroundings:
local function makeCounter()
  local count = 0
  return function ()
    count = count + 1
    return count
  end
end
local next = makeCounter()
print(next(), next(), next())    -- 1  2  3

-- Variadic functions:
local function sum(...)
  local total = 0
  for _, n in ipairs({ ... }) do
    total = total + n
  end
  return total
end
print(sum(1, 2, 3, 4))   -- 10
✦ Tip
s:upper() is sugar for string.upper(s) — the colon passes the value as a hidden first argument. You'll meet it again with objects in the OOP lesson.