Next: 4.7 Fallbacks Up: 4 The Language Previous: 4.5 Expressions

4.6 Function Definitions

Functions in Lua can be defined anywhere in the global level of a module. The syntax for function definition is:

   function ::= function name '(' [ parlist1 ] ')' block end

When Lua finds a function definition, its body is compiled to intermediate code and stored, with type function, into the global variable name.

Parameters act as local variables, initialized with the argument values.

   parlist1 ::= 'name' { ',' name }

Results are returned using the return statement (see Section 4.4.3). If control reaches the end of a function without a return instruction, the function returns with no results.

There is a special syntax for definition of methods, that is, functions which are to be stored in table fields.

   function ::= function name ':' name '(' [ parlist1 ] ')' block end
A declaration like
function t:f (...) 
  ... 
end
is equivalent to
function temp (self, ...)
  ...
end
t.f = temp
that is, the function is created with a dummy name and then assigned to the field f of the table t. Moreover, the function gets an extra formal parameter called self. Notice that the variable t must be previously initialized with a table value.

Next: 4.7 Fallbacks Up: 4 The Language Previous: 4.5 Expressions