Lua Cheatsheet

Functions

Use this Lua reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Defining Functions

local function add(a, b)
  return a + b
end

print(add(2, 3))

Equivalent long form:

local add
add = function(a, b)
  return a + b
end

The predeclaration matters for recursive local functions.

Parameters and Return Values

local function greet(name)
  name = name or "friend"
  return "Hello, " .. name
end

Missing arguments become nil. Extra arguments are ignored unless captured with varargs.

Multiple Returns

local function minmax(a, b)
  if a < b then return a, b end
  return b, a
end

local lo, hi = minmax(9, 4)

Multiple returns flatten in call position:

print(minmax(9, 4))       -- prints both values
local t = {minmax(9, 4)}  -- table contains both values

Varargs

local function sum(...)
  local total = 0
  for _, n in ipairs({...}) do
    total = total + n
  end
  return total
end

{...} is fine when no argument can be nil — a nil punches a hole and ipairs/# stop early. The nil-safe tools:

select("#", ...)             -- exact argument count, nils included
select(2, ...)               -- arguments from position 2 onward
local args = table.pack(...) -- table with the args plus n = count (5.2+)
for i = 1, args.n do
  print(args[i])             -- visits nil arguments too
end
print(table.unpack(args, 1, args.n))

In Lua 5.1 and LuaJIT, unpack is a global rather than table.unpack, and table.pack does not exist (use {n = select("#", ...), ...}).

Closures

local function make_counter()
  local count = 0
  return function()
    count = count + 1
    return count
  end
end

local next_id = make_counter()
print(next_id()) -- 1
print(next_id()) -- 2

Inner functions capture locals from outer functions.

Method Syntax

local account = { balance = 0 }

function account:deposit(amount)
  self.balance = self.balance + amount
end

account:deposit(25)              -- passes account as self
account.deposit(account, 25)     -- equivalent

Use : when the function expects self; use . for ordinary table functions.

Tail Calls

Lua supports proper tail calls when a function directly returns another function call.

local function loop(n)
  if n == 0 then return "done" end
  return loop(n - 1)
end