CodeToLive

Control Structures in Lua

Control structures allow you to control the flow of your program's execution. Lua provides standard control structures like conditionals and loops with a clean syntax.

Conditional Statements

Lua has an if-elseif-else structure for conditionals:

local age = 18

if age < 13 then
    print("Child")
elseif age < 18 then
    print("Teenager")
else
    print("Adult")
end

Logical Operators

Lua provides the following logical operators:

  • and - logical AND
  • or - logical OR
  • not - logical NOT
if age > 12 and age < 20 then
    print("Teenage years")
end

Loops

Lua has several loop structures:

while loop

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

repeat-until loop

This is Lua's version of a do-while loop:

local j = 1
repeat
    print(j)
    j = j + 1
until j > 5

for loop

Lua has numeric and generic for loops:

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

-- Numeric for with step
for i = 10, 1, -2 do
    print(i)
end

-- Generic for (iterates over tables)
local days = {"Sunday", "Monday", "Tuesday"}
for k, v in ipairs(days) do
    print(k, v)
end

break and return

Use break to exit a loop and return to exit a function:

for i = 1, 10 do
    if i == 5 then
        break
    end
    print(i)
end

Next Steps

Now that you understand control structures, learn about functions in Lua.