BudiBadu Logo
Samplebadu

Lua by Example: Functions

Lua 5.4

Functions in Lua are first-class values. This sample demonstrates definition, multiple return values, and anonymous functions.

Code

-- Basic function
function add(a, b)
    return a + b
end

-- Anonymous function assigned to a variable
local subtract = function(a, b)
    return a - b
end

-- Function returning multiple values
function getBounds()
    return 0, 100
end

local min, max = getBounds()

-- Variable arguments (...)
function sum(...)
    local s = 0
    for _, v in ipairs({...}) do
        s = s + v
    end
    return s
end

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

Explanation

In Lua, functions are first-class citizens, meaning they can be stored in variables, passed as arguments to other functions, and returned as results. A function definition like function foo() ... end is actually syntactic sugar for assigning an anonymous function to a variable: foo = function() ... end.

One of Lua's distinctive features is the ability to return multiple results from a single function. This is extremely convenient for returning a value and an error status, or for returning coordinates like x and y. You can capture these values using multiple assignment.

Lua also supports variable arguments using the ellipsis ... syntax. Inside the function, ... represents the list of extra arguments, which can be packed into a table or iterated over directly. This allows for flexible function signatures similar to printf in C.

Code Breakdown

13
return 0, 100 pushes two values onto the stack to be returned to the caller.
21
{...} collects all variable arguments into a new table (list).