If Else in Lua

Our first program will demonstrate the use of if/else statements in Lua. Here’s the full source code:

-- Here's a basic example.
if 7 % 2 == 0 then
    print("7 is even")
else
    print("7 is odd")
end

-- You can have an if statement without an else.
if 8 % 4 == 0 then
    print("8 is divisible by 4")
end

-- Logical operators like 'and' and 'or' are often useful in conditions.
if 8 % 2 == 0 or 7 % 2 == 0 then
    print("either 8 or 7 are even")
end

-- A variable can be declared before conditionals and used in all branches.
local num = 9
if num < 0 then
    print(num .. " is negative")
elseif num < 10 then
    print(num .. " has 1 digit")
else
    print(num .. " has multiple digits")
end

To run the program, save the code in a file named if_else.lua and use the Lua interpreter:

$ lua if_else.lua
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Lua, you don’t need parentheses around conditions, but you do need to use then and end to define the scope of the if statement. The elseif keyword is used for additional conditions.

Lua doesn’t have a ternary operator, so you’ll need to use a full if statement even for basic conditions.