Lesson 3: Control Structures in Lua

April 22, 2024

Welcome back to our Lua programming series! In this lesson, we will delve into the world of control structures in Lua. Control structures are essential for determining the flow of execution in a program. Let’s explore conditional statements, loops, and logical operators in Lua.

Conditional Statements: if-else

Conditional statements allow us to make decisions in our code based on certain conditions. In Lua, the syntax for an if-else statement is as follows:

if <condition> then
    <!-- code block -->
elseif <condition> then
    <!-- code block -->
else
    <!-- code block -->
end

Here’s an example to illustrate the usage of if-else in Lua:

local num = 10
if num > 0 then
    print("Number is positive")
else
    print("Number is non-positive")
end

Loops: while, for

Loops are used to execute a block of code repeatedly. Lua supports both while and for loops. The syntax for a while loop is:

while <condition> do
    <!-- code block -->
end

For example:

local i = 1
while i <= 5 do
    print(i)
    i = i + 1
end

The syntax for a for loop is:

for i = 1, 5 do
    <!-- code block -->
end

Here’s an example of a for loop:

for i = 1, 5 do
    print(i)
end

Logical Operators

Logical operators are used to combine multiple conditions. Lua supports logical operators such as ‘and’, ‘or’, and ‘not’. Here’s an example:

local x = 10
local y = 5
if x > 0 and y > 0 then
    print("Both x and y are positive")
end

With a good understanding of control structures, you can effectively control the flow of your Lua programs. Practice writing code using conditional statements, loops, and logical operators to master the art of programming in Lua. Stay tuned for more lessons in our Lua programming series!