function add(a, b)
return a + b
end
-- creates a function called add, which returns the sum of it's two arguments
Let's look at the syntax.
First, we see a function
keyword. Well, that's pretty descriptive. Next we see the add
identifier; the name. We then see the arguments (a, b)
these can be anything, and they are local. Only inside the function body can we access them. Let's skip to the end, we see... well, the end
! And all that's in between is the function body; the code that's ran when it is called. The return
keyword is what makes the function actually give some useful output. Without it, the function returns nothing, which is equivalent to returning nil. This can of course be useful for things that interact with IO, for example:
function printHello(name)
print("Hello, " .. name .. "!");
end
In that function, we did not use the return statement.
Functions can also return values conditionally, meaning that a function has the choice of returning nothing (nil) or a value. This is demonstrated in the following example.
function add(a, b)
if (a + b <= 100) then
return a + b -- Returns a value
else
print("This function doesn't return values over 100!") -- Returns nil
end
end
It is also possible for a function to return multiple values seperated by commas, as shown:
function doOperations(a, b)
return a+b, a-b, a*b
end
added, subbed, multiplied = doOperations(4,2)
Functions can also be declared local
do
local function add(a, b) return a+b end
print(add(1,2)) --> prints 3
end
print(add(2, 2)) --> exits with error, because 'add' is not defined here
They can be saved in tables too:
tab = {function(a,b) return a+b end}
(tab[1])(1, 2) --> returns 3