Lua Functions: Parameters, Multiple Returns, Varargs and Tail Calls
Define and Call Lua Functions
Functions are first-class values in Lua. They can be stored in tables, passed as arguments, returned from other functions, and created anonymously.
The declaration above assigns a function value to a local name. Prefer local functions unless a global API is intentional.
Multiple results
A function call produces all results only in certain positions, such as the final expression of an assignment, argument list, or return statement. Parentheses force a call to one result: (divide(17, 5)).
Variadic functions
select("#", ...) preserves the count even when arguments include nil. {...} does not by itself preserve trailing nil values.
Lua has positional parameters, but a table provides readable named options:
Recursion and tail calls
A call is in tail position when its results are returned directly:
Proper tail calls reuse stack space. Adding arithmetic, another result, or work after the call removes tail position. Use recursion where it expresses the structure clearly, but prefer loops for simple linear traversal.