Function Definition


Like most programming languages, Lua supports the ability to add new functionality by implementing functions. At a high-level, functions are "callable units" of code that can optionally accept 1 or more parameters, perform some operations on them, then optionally return 0 or more results.

Lua supports two different, but equivalent, styles for defining functions. The first style creates a variable then assigns a function to that variable:

-- local name = function(args)

local sum = function(a, b)
    -- function body
    return a + b
end

The second style is equivalent to the first, but the order of the function keyword and the variable name are reversed.

-- local function name(args)

local function diff(a, b)
    --function body
    return a - b
end

In both cases, the function's arguments are defined as a sequence of 0 or more comma-separated variable names in the function definition.

Which style to use is generally a matter of personal coding style, but the second style allows functions to be stored in tables which allows them to operate as "methods" when implementing classes with Lua.