Easy Tutorial
❮ Lua Nested Loops Lua Iterators ❯

Lua Functions

In Lua, functions are the primary method for abstracting statements and expressions. They can be used to perform specific tasks or to compute values.

Lua provides many built-in functions that you can easily call in your programs, such as the print() function, which prints the passed arguments to the console.

Lua functions serve two main purposes:

Function Definition

The format for defining a function in Lua programming language is as follows:

optional_function_scope function function_name(argument1, argument2, argument3, ..., argumentn)
    function_body
    return result_params_comma_separated
end

Explanation:

Example

The following example defines the function max(), which takes parameters num1 and num2, compares their values, and returns the maximum value:

--[[ Function returns the maximum value of two numbers --]]
function max(num1, num2)
    if (num1 > num2) then
        result = num1;
    else
        result = num2;
    end
    return result;
end
-- Call the function
print("The maximum value between the two is ", max(10, 4))
print("The maximum value between the two is ", max(5, 6))

The above code execution results are:

The maximum value between the two is  10
The maximum value between the two is  6

In Lua, we can pass functions as arguments to other functions, as shown in the following example:

myprint = function(param)
    print("This is the print function - ##", param, "##")
end

function add(num1, num2, functionPrint)
    result = num1 + num2
    -- Call the passed function parameter
    functionPrint(result)
end
myprint(10)
-- Pass the myprint function as an argument
add(2, 5, myprint)

The above code execution results are:

This is the print function - ## 10 ##
This is the print function - ## 7 ##

Multiple Return Values

Lua functions can return multiple result values, such as string.find, which returns the start and end indices of the matched substring (or nil if no match is found).

> s, e = string.find("www.tutorialpro.org", "tutorialpro")
> print(s, e)
5 10

To return multiple values in a Lua function, list the values to be returned after return, as shown below:

function maximum(a)
    local mi = 1             -- Maximum value index
    local m = a[mi]          -- Maximum value
    for i, val in ipairs(a) do
        if val > m then
            mi = i
            m = val
        end
    end
    return m, mi
end

print(maximum({8, 10, 23, 12, 5}))

The above code execution results are:

23 3

Variable Arguments

Lua functions can accept a variable number of arguments, similar to C language. Use three dots ... in the function parameter list to indicate variable arguments.

function add(...)
    local s = 0
    for i, v in ipairs{...} do   --> {...} represents an array of all variable arguments
        s = s + v
    end
    return s
end
print(add(3, 4, 5, 6, 7))  ---> 25

We can assign variable arguments to a variable. For example, to calculate the average of several numbers:

function average(...)
    result = 0
    local arg = {...}    --> arg is a table, a local variable
    for i, v in ipairs(arg) do
        result = result + v
    end
    print("Total number of arguments passed " .. #arg .. " numbers")
    return result / #arg
end

print("The average is", average(10, 5, 3, 4, 5, 6))

The above code execution results are:

Total number of arguments passed 6 numbers
The average is 5.5

We can also get the number of variable arguments using select("#", ...):

function average(...)
    result = 0
    local arg = {...}
    for i, v in ipairs(arg) do
        result = result + v
    end
    print("Total number of arguments passed " .. select("#", ...) .. " numbers")
    return result / select("#", ...)
end

print("The average is", average(10, 5, 3, 4, 5, 6))

The above code execution results are:

Total number of arguments passed 6 numbers
The average is 5.5

Sometimes we may need a few fixed parameters followed by variable arguments. Fixed parameters must precede variable arguments:

function fwrite(fmt, ...)  --> Fixed parameter fmt
    return io.write(string.format(fmt, ...))
end

fwrite("tutorialpro\n")    --> fmt = "tutorialpro", no variable arguments
fwrite("%d%d\n", 1, 2)     --> fmt = "%d%d", variable arguments are 1 and 2

The output results are:

tutorialpro
12

Typically, we use {...} to iterate over variable arguments. However, variable arguments may contain nil, so we can use the select function to access variable arguments: select('#', ...) or select(n, ...)

When calling select, you must pass a fixed argument selector (the selection switch) and a series of variable arguments. If selector is a number n, select returns all arguments from index n to the end. If selector is the string #, select returns the total number of variable arguments.

function f(...)
    a = select(3, ...)  --> Starting from the third position, variable a corresponds to the first argument in the right-hand list
    print(a)
    print(select(3, ...))  --> Print all list arguments
end

f(0, 1, 2, 3, 4, 5)

The output results are:

2
2 3 4 5
do
    function foo(...)
        for i = 1, select('#', ...) do  --> Get the total number of arguments
            local arg = select(i, ...);  --> Read the argument, arg corresponds to the first argument in the right-hand list
            print("arg", arg);
        end
    end

    foo(1, 2, 3, 4);
end

The output results are:

arg 1
arg 2
arg 3
arg 4
❮ Lua Nested Loops Lua Iterators ❯