Game Development Reference
In-Depth Information
Functions are self-contained chunks of execution, much like they are in C or C++.
One big difference is that functions are also first-class objects in Lua, which means
they are treated like any other variable. You can assign them to other variables, pass
them as parameters to other functions, and so on.
Functions are declared using the
function
keyword, followed by the function name.
Parentheses are used to enclose any variables the function expects. Functions can
return anything or nothing at all. They can return multiple values as well. If a func-
tion doesn
'
t explicitly return, it returns
nil
by default. If you call a function without
enough parameters, the extra parameters will all be
nil
. If you call a function with
too many parameters, the extra parameters passed in are ignored.
Here
'
s a simple function:
function Square(val)
return val * val
end
This function returns the square of the number you pass in. In reality, what this
statement is really doing is creating a function and assigning a pointer to that func-
tion to a variable called
Square
. You call the function like you would call a function
in C.
x = Square(5)
print(x) -- > prints 25
Since
Square
is really just a variable pointing to a function, you can treat it like any
other variable.
x = Square -- no parentheses; x is now pointing to the same function
print(type(x)) -- > prints
“
function
”
Square = x(5)
print(Square) -- > prints 25
In fact, the syntax you
ve seen thus far for writing functions is just syntax sugar to
make it a bit more readable. The more explicit way a function is defined is as
follows:
'
Square = function(val) return val * val end
As far as the Lua interpreter is concerned, there
s no difference between the two. The
first form is a bit more readable, but the second form can be handy when assigning
functions to a table or generating anonymous functions as parameters to other
functions.
'