A function call in Lua has the following syntax:
functioncall ::= prefixexp args
In a function call, first prefixexp and args are evaluated. If the value of prefixexp has type function, then this function is called with the given arguments. Otherwise, the prefixexp "call" metamethod is called, having as first parameter the value of prefixexp, followed by the original call arguments (see Metatables).
The form
functioncall ::= prefixexp `*:*` Name args
can be used to call "methods". A call v:name(args)
is syntactic sugar for v.name(v,args)
, except that v
is evaluated only once.
Arguments have the following syntax:
args ::= `*(*` [explist1] `*)*` args ::= tableconstructor args ::= String
All argument expressions are evaluated before the call. A call of the form f{_fields_}
is syntactic sugar for f({_fields_})
; that is, the argument list is a single new table. A call of the form f'_string_'
(or f"_string_"
or f[[string]]
) is syntactic sugar for f('_string_')
; that is, the argument list is a single literal string.
As an exception to the free-format syntax of Lua, you cannot put a line break before the '=(=' in a function call. This restriction avoids some ambiguities in the language. If you write
a = f (g).x(a)
Lua would see that as a single statement, a = f(g).x(a)
. So, if you want two statements, you must add a semi-colon between them. If you actually want to call f
, you must remove the line break before (g)
.
A call of the form return
functioncall is called a tail call. Lua implements proper tail calls (or proper tail recursion): in a tail call, the called function reuses the stack entry of the calling function. Therefore, there is no limit on the number of nested tail calls that a program can execute. However, a tail call erases any debug information about the calling function. Note that a tail call only happens with a particular syntax, where the return has one single function call as argument; this syntax makes the calling function return exactly the returns of the called function. So, none of the following examples are tail calls:
return (f(x)) -- results adjusted to 1 return 2 * f(x) return x, f(x) -- additional results f(x); return -- results discarded return x or f(x) -- results adjusted to 1