Lua

Lua: Functions

Functions, as in other languages, are used to group statements and expressions to do some common work.

Defining functions

A function definition looks like this.

function add(x, y)
  local z = x + y
  return z
end

Functions do not need to return a value. If they do not return a value, you will see them written as a statement. If they do return a value you will see them used as part of an expression.

Calling functions

A function call is indicated by a list of arguments in parentheses after the function name.

a = add(10, 3)
print(a)

Here, add is the function defined above and is used as an expression with the result stored in variable a. And, print is a system provided function that will write the contents of variable a to standard out.

There is a shorthand notation where if the function has a single argument and the argument is either a literal string or a table constructor then the parentheses are optional.

If a function is called with too many parameters, Lua will throw away extra parameters.

If a function is called with too few parameters, Lua will provide the value nil for the missing parameters.

Multiple return values

Functions in Lua can return multiple results.

Variadic parameters

Lua functions can take a variable number of parameters.

Tools

Web

Languages

Data