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 chunk. The syntax for function definition is:


functionfunction var ( parlist1 )
  block end

When Lua pre-compiles a chunk, all its function bodies are pre-compiled, too. Then, when Lua ``executes'' the function definition, its body is stored, with type function, into the variable var .

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


parlist1name , 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 have an extra parameter self.


functionfunction var : name ( parlist1
  ) block end
A declaration like
function v:f (...)
  ...
end
is equivalent to
function v.f (self, ...)
  ...
end
that is, the function gets an extra formal parameter called self . Notice that the variable v must have been previously initialized with a table value.


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