Table of Contents
Control Structures and Functions in Lua
1. Conditional Statements
Conditional statements allow your program to make decisions based on certain conditions. In Lua, you use if, elseif, and else to implement conditional logic.
If Statement
The if statement evaluates a condition and executes a block of code if the condition is true. Code Example:
local devLevel = 18 if devLevel >= 18 then print("WOW! REALLY GREAT") end
Explanation:
- if devLevel >= 18 then: This line checks if the variable age is greater than or equal to 18.
- print(“WOW! REALLY GREAT”): If the condition (devLevel >= 18) is true, then this line will execute and print “WOW! REALLY GREAT”
Elseif and Else Statements
You can use elseif to check additional conditions and else to provide a default action if none of the conditions are true.
Code Example:
local temperature = 25 if temperature > 30 then print("It's hot outside!") elseif temperature > 20 then print("It's warm outside.") else print("It's cool outside.") end
Exercise:
- Write an if statement to check if a variable number is positive.
- Extend the if statement with elseif and else to cover different ranges of values.
- Modify the variables and test different conditions to see the output.
Example Exercise Code:
local number = 10 if number > 0 then print("The number is positive.") elseif number < 0 then print("The number is negative.") else print("The number is zero.") end
2. Loops
Loops are used to repeat a block of code multiple times. Lua supports while, for, and repeat…until loops.
While Loop
The while loop repeats a block of code while a condition is true.
Code Example:
local i = 1 while i <= 5 do print("i = " .. i) i = i + 1 end
Explanation:
- local i = 1: Initializes a variable i with a value of 1.
- while i ⇐ 5 do: This line sets up the condition to execute the loop as long as i is less than or equal to 5.
- print(“i = ” .. i): Prints the current value of i.
- i = i + 1: Increments i by 1 in each iteration to avoid an infinite loop.
For Loop
The for loop iterates over a range of values specified by the user.
Code Example:
for i = 1, 5 do print("i = " .. i) end
Explanation:
- for i = 1, 5 do: This line initializes i to 1 and iterates up to 5.
- print(“i = ” .. i): Prints the current value of i in each iteration.
Repeat...Until Loop
The repeat…until loop executes a block of code at least once and continues to repeat until a condition becomes true.
Code Example:
local i = 1 repeat print("i = " .. i) i = i + 1 until i > 5
Explanation:
- repeat: Starts the loop block.
- print(“i = ” .. i): Prints the current value of i.
- i = i + 1: Increments i by 1 in each iteration.
- until i > 5: Ends the loop when i becomes greater than 5.
Exercise:
- Write a while loop to count from 10 to 1 and print each number.
- Use a for loop to print even numbers from 1 to 10.
- Implement a repeat…until loop to prompt the user for input until they enter a valid number.
Example Exercise Code:
-- while loop local countdown = 10 while countdown >= 1 do print(countdown) countdown = countdown - 1 end -- for loop for i = 2, 10, 2 do print(i) end -- repeat...until loop local userInput repeat print("Enter a number: ") userInput = io.read("*n") -- Read a number from input until userInput ~= nil print("You entered: " .. userInput)
3. Functions
Functions are blocks of code that perform a specific task and can be reused throughout your program. They help in organizing code and making it more readable.
Defining Functions
You define a function in Lua using the function keyword followed by the function name and parameters.
Code Example:
-- Function to calculate the square of a number function square(num) return num * num end -- Calling the function local result = square(5) print("Square: " .. result) -- prints: 25
Explanation:
- function square(num): Defines a function named square that takes a parameter num.
- return num * num: Computes the square of num and returns the result to the caller.
Parameters and Return Values
Functions can have parameters (input values) and return values (output values).
Code Example:
-- Function with parameters and return value function greet(name) return "Hello, " .. name .. "!" end -- Calling the function local message = greet("Lua Learner") print(message) -- prints: Hello, Lua Learner!
Exercise:
- Write a function that calculates the area of a rectangle given its length and width.
- Create a function that converts Celsius to Fahrenheit.
- Implement a function that checks if a number is prime and returns true or false.
Example Exercise Code:
-- Function to calculate the area of a rectangle function calculateArea(length, width) return length * width end -- Function to convert Celsius to Fahrenheit function celsiusToFahrenheit(celsius) return celsius * 9 / 5 + 32 end -- Function to check if a number is prime function isPrime(number) if number <= 1 then return false elseif number == 2 then return true else for i = 2, math.sqrt(number) do if number % i == 0 then return false end end return true end end -- Example usage local area = calculateArea(5, 10) print("Area of rectangle: " .. area) local fahrenheitTemp = celsiusToFahrenheit(25) print("Temperature in Fahrenheit: " .. fahrenheitTemp) local num = 17 if isPrime(num) then print(num .. " is a prime number.") else print(num .. " is not a prime number.") end