A complete introduction to scripting for games using the versatile Lua programming language and the Core game development platform. Add an array of game coding skills to your toolbox and take your game development to new heights!
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.
function talkAboutYourDay() print("It was a good day!") end
To call a function, you write its name, followed by
function talkAboutYourDay() print("It was a good day!") end talkAboutYourDay() -- this will print "It was a good day"
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.
function wishAHappyDay(day) print("Happy " .. day) end wishAHappyDay("birthday") -- prints "Happy birthday" wishAHappyDay("Tuesday") -- prints "Happy tuesday"
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.
function averageTwoNumbers(aNumber, anotherNumber) local total = aNumber + anotherNumber local average = total / 2 return average end