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.

Creating Functions

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.

Define a Function

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!")
endCode language: Lua (lua)

Call a Function

To call a function, you write its name, followed by (). Example:

function talkAboutYourDay() 
    print("It was a good day!")

talkAboutYourDay() -- this will print "It was a good day"Code language: Lua (lua)

Inputs and Outputs

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)

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. Using the return keyword also allows you to retrieve the result of the function. An example is given in the following code snippet.


function averageTwoNumbers(aNumber, anotherNumber)
    local total = aNumber + anotherNumber
    local average = total / 2

    return average

local result = averageTwoNumbers(2,8)
print(result) -- displays 5Code language: Lua (lua)

More Examples

local playerHp = 100

function hitPlayer(nbDamage)
    playerHp = playerHp - nbDamage
    -- If the HP are going below 0, the value is set to 0 because HP can't be negative
    if playerHp < 0 then
        playerHp = 0

function showPlayerStatus()
   if playerHp <= 0 then
       print("Player is dead.")
       return -- stop the function here, the code below is not executed
   print("Player has "..playerHp.." HP.")

showPlayerStatus() -- Prints "Player has 100 HP."
showPlayerStatus() -- Prints "Player has 75 HP."
showPlayerStatus() -- Prints "Player is dead."Code language: Lua (lua)
Post a comment

Leave a Comment

Scroll to Top