Function Definitions

<< Click to Display Table of Contents >>

Navigation:  Multi-Protocol MasterOPC Server > Lua 5.1 Reference Manual > The Language and syntax > Expressions >

Function Definitions

A function definition has the following syntax:

function (arguments)

funcbody --function body

end

Function parameters (arguments) are, in fact, local variables initialized with input values.

When a function is called, the list of arguments is adjusted to the length of the list of parameters, unless the function is a variadic or vararg function, which is indicated by three dots (’...’) at the end of its parameter list. A vararg function does not adjust its argument list; instead, it collects all extra arguments and supplies them to the function through a vararg expression, which is also written as three dots. The value of this expression is a list of all actual extra arguments, similar to a function with multiple results. If a vararg expression is used inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element. If the expression is used as the last element of a list of expressions, then no adjustment is made (unless that last expression is enclosed in parentheses).

As an example, consider the following definitions:

function f(a, b) end

function g(a, b, ...) end

function r() return 1,2,3 end

Then, we have the following mapping from arguments to parameters and to the vararg expression:

 

CALL             PARAMETERS

f(3)             a=3, b=nil

f(3, 4)          a=3, b=4

f(3, 4, 5)       a=3, b=4

f(r(), 10)       a=1, b=10

f(r())           a=1, b=2

g(3)             a=3, b=nil, ... -->  (nothing)

g(3, 4)          a=3, b=4,   ... -->  (nothing)

g(3, 4, 5, 8)    a=3, b=4,   ... -->  5  8

g(5, r())        a=5, b=1,   ... -->  2  3

Results are returned using the return statement (see Control Structures ). If control reaches the end of a function without encountering a return statement, then the function returns with no results.

The colon syntax is used for defining methods, that is, functions that have an implicit extra parameter self. Thus, the statement

function t.a.b.c:f (params) body end

is syntactic sugar for

t.a.b.c.f = function (self, params) body end