Lua If Else Elseif Conditions

In this article, we will explore Lua If Else and Elseif statements  and provide examples of how they are used in Lua programming language.

Lua If Else and Elseif statements allow programs to make decisions and execute different blocks of code depending on certain conditions.

These statements enable you to create more intelligent and dynamic lua programs that can respond to changing inputs and conditions.

In Lua, you can make decisions using conditional statements such as if, elseif, and else.



Lua if Statement

Lua if statements are used to execute a block of code only if a certain condition is met.

Syntax

if condition then
-- code block executed only if condition is true
end

Here is an example that uses an if statement to check if a number is divisible by 2:

Example: 

num = 6if num % 2 == 0 then print(num .. " is divisible by 2") end

Lua If else Statement

Lua also supports an else clause, which allows you to specify what to do if the condition is false.

Syntax

if condition then
-- code block executed only if condition is true
else
-- code block executed only if condition is false
end

The following example demonstrates the else statement in Lua:

Example: 

num = 7if num % 2 == 0 then print(num .. " is divisible by 2") else print(num .. " is not divisible by 2") end

Lua elseif Statement

Using the elseif statement, we can check for additional conditions after the initial if statement.

Syntax

if condition1 then
-- code block executed only if condition1 is true
elseif condition2 then
-- code block executed only if condition2 is true
else
-- code block executed only if all above conditions are false
end

Below example illustrates the usage of elseif statement in Lua:

Example: 

num = -5if num > 0 then print(num .. " is positive") elseif num < 0 then print(num .. " is negative") else print(num .. " is zero") end
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
1

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *