If-then-else in Lua Programming


An if statement in Lua is used to evaluate some code based on some conditions. If those conditions match, then we execute the code that is written inside the code block of an if statement, else we do nothing.

In Lua, the if statement tests its condition and if that condition evaluates to true, then it executes its then-part or its else-part.

The else-part is optional in Lua.

Example

Consider the example shown below −

a = -1

if a < 0 then
   a = 0
end

print(a)

Output

0

We can also insert an else-part in the above statement to make it more explanatory and useful.

Example

Consider the example shown below −

a = 10

if a < 0 then
   a = 0
else
   a = 1
end
print(a)

Output

1

It should be noted that we terminate the if-else statements in Lua with the end keyword.

We can also have multiple if-else statements in a nested form. In that case, we make use of the elseif keyword.

Example

Consider the example shown below as reference −

a = 1
b = 2
op = "/"
if op == "+" then
   r = a + b
elseif op == "-" then
   r = a - b
elseif op == "*" then
   r = a*b
elseif op == "/" then
   r = a/b
else
   error("invalid operation")
end

print(a/b)

Output

0.5

Updated on: 01-Dec-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements