Functions in Lua can be defined anywhere in the global level of a module. The syntax for function definition is:
function ::= function 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.
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 have an extra parameter self.
function ::= function var ':' name '(' [ parlist1 ] ')' block endA declaration like
function v:f (...) ... endis equivalent to
function v.f (self, ...) ... endthat is, the function gets an extra formal parameter called self. Notice that the variable v must be previously initialized with a table value.