Functions are a way to write a section of code for a particular purpose. They are like recipes you create for what you should do in a particular setting, they can be re-used throughout your program.
Defining a function is writing what the instructions should be for this function. Calling a function is when you tell the program to actually do that code.
To create a function you use the function
keyword, followed by a name, and then ()
. Code that is part of the function needs to be indented, and then you use the keyword end
to specify that this is all of the code.
Example:
function talkAboutYourDay()
print("It was a good day!")
end
Code language: Lua (lua)
To call a function, you write its name, followed by ()
.
Example:
function talkAboutYourDay()
print("It was a good day!")
end
talkAboutYourDay() -- this will print "It was a good day"
Code language: Lua (lua)
It is convenient to be able to label and re-use code, but functions can also take in inputs, called parameters and change their behavior based on them. They can also send back data as an output, called a return.
Parameters are written between the ()
of the function. When you define the function, you give a label to the input, which is like a variable that gets assigned to whatever is between the ()
when you call the function.
Examples
function wishAHappyDay(day)
print("Happy " .. day)
end
wishAHappyDay("birthday") -- prints "Happy birthday"
wishAHappyDay("Tuesday") -- prints "Happy tuesday"
Code language: Lua (lua)
To create a return, you use the return keyword. This will immediately stop your function, so it is usually the last line of the function.
Examples:
function averageTwoNumbers(aNumber, anotherNumber)
local total = aNumber + anotherNumber
local average = total / 2
return average
end
Code language: Lua (lua)