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!")
endThis 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
EasyCreate 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!")
endThe 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()This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators 2 Relational & Logic
Equality OperatorsRelational OperatorsThe 'and' OperatorThe 'or' OperatorThe 'not' OperatorShort-Circuit EvaluationTruthy and Falsy ValuesRecap - Simple Logic7Basic Conditional Logic
The if-then StatementThe if-then-else StatementThe elseif StatementRecap - Treasure Chest2Variables and Data Types
What is a Variable?NumbersStringsBooleansThe Value 'nil'The type() FunctionNaming ConventionsRecap - Character Profile5Basic Output
Printing LiteralsPrinting VariablesPrinting Multiple ValuesCombining Strings & VariablesThe tostring() FunctionInputCastRecap - Status ReportRecap - Till 1208String Manipulation Basics
string.len()string.upper & string.lowerstring.sub()string.rep()string.find()Recap - Format Username3Operators 1 Arithmetic & Conc
Arithmetic OperatorsModulo OperatorExponentiation OperatorString ConcatenationOperator PrecedenceRecap - Simple Calculations6Project: Character Stats Disp
Welcome MessageDeclare Character Stats9Functions Basics
Declaring a FunctionCalling a FunctionFunctions with ParametersFunctions with Multiple ParamsThe 'return' StatementRecap - Area Calculator