CodeToLive

Functions in Lua

Functions are the main mechanism for abstraction and code reuse in Lua. They can be assigned to variables, passed as arguments, and returned as results.

Defining Functions

The basic syntax for defining a function in Lua:

-- Named function
function greet(name)
    return "Hello, " .. name .. "!"
end

-- Anonymous function assigned to a variable
local greet = function(name)
    return "Hello, " .. name .. "!"
end

Calling Functions

Functions can be called with or without parentheses (in some cases):

print(greet("Alice"))  -- With parentheses
print greet "Alice"   -- Without parentheses for single string argument

Multiple Return Values

Lua functions can return multiple values:

function getDimensions()
    return 10, 20  -- Returns width and height
end

local width, height = getDimensions()

Variable Number of Arguments

Use ... to accept a variable number of arguments:

function sum(...)
    local result = 0
    local args = {...}
    for i, v in ipairs(args) do
        result = result + v
    end
    return result
end

print(sum(1, 2, 3, 4))  -- 10

First-Class Functions

Functions are first-class values in Lua, meaning they can be:

  • Stored in variables
  • Passed as arguments
  • Returned from other functions
-- Higher-order function example
function applyOperation(x, y, operation)
    return operation(x, y)
end

local result = applyOperation(5, 3, function(a, b) return a * b end)

Closures

Lua supports closures - functions that can access variables from their enclosing scope:

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

local counter = makeCounter()
print(counter())  -- 1
print(counter())  -- 2

Tail Calls

Lua supports proper tail calls, which allow for efficient recursion:

function factorial(n, acc)
    acc = acc or 1
    if n <= 1 then
        return acc
    else
        return factorial(n - 1, n * acc)  -- Tail call
    end
end

Next Steps

Now that you understand functions, learn about tables and metatables in Lua.