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:

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:

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:

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:

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:

Exercise:

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:

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:

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