Menu
Coddy logo textTech

Declaring a Function

Part of the Fundamentals section of Coddy's Lua journey — lesson 50 of 90.

Functions are one of the most powerful tools in programming. Think of a function as a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you can create a function once and use it whenever needed.

In Lua, you declare a function using the function keyword, followed by the function name, and ending with the end keyword:

function displayWelcomeMessage()
    print("Welcome to the game!")
end

This creates a function named displayWelcomeMessage that contains a single line of code. The parentheses () after the function name are required, even when the function doesn't take any inputs.

challenge icon

Challenge

Easy

Create a game notification system by declaring a function that displays a welcome message to players. Declare a function named showGameWelcome that contains a single print() statement to output "Welcome to Adventure Quest!". Remember that declaring the function creates it but doesn't execute the code inside - the function is ready to be called later.

Cheat sheet

Functions are reusable blocks of code that perform specific tasks. In Lua, declare a function using the function keyword and end with end:

function displayWelcomeMessage()
    print("Welcome to the game!")
end

The parentheses () after the function name are required, even when the function doesn't take any inputs. Declaring a function creates it but doesn't execute the code inside.

Try it yourself

-- TODO: Write your code here to declare the showGameWelcome function

-- Call the function to display the welcome message
showGameWelcome()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals