Lua Control Flow Guide — if, elseif, and Conditional Logic
In this tutorial, you will learn about Lua Control Flow Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Lua control flow uses the if keyword followed by a condition, then optionally elseif and else branches, all terminated with end -- supporting comparison operators and logical combinations for complex branching logic.
Basic if Statement
local score = 85
if score >= 60 then
print("Passed")
end
if-else
local age = 17
if age >= 18 then
print("Adult")
else
print("Minor")
end
if-elseif-else
local grade = 75
if grade >= 90 then
print("A")
elseif grade >= 80 then
print("B")
elseif grade >= 70 then
print("C")
elseif grade >= 60 then
print("D")
else
print("F")
end
Nested Conditions
local user = { role = "admin", active = true }
if user.active then
if user.role == "admin" then
print("Full access granted")
elseif user.role == "editor" then
print("Edit access granted")
else
print("Read-only access")
end
else
print("Account disabled")
end
Comparison Operators
-- Relational
print(5 == 5) --> true
print(5 ~= 5) --> false (not equal)
print(5 < 10) --> true
print(5 <= 5) --> true
print(10 > 5) --> true
print(10 >= 5) --> true
-- String comparison (lexicographic)
print("apple" < "banana") --> true
Common Mistakes
1. Using = instead of ==
= is assignment, == is equality. if x = 5 then is a syntax error.
2. Forgetting then
Every if and elseif must have then before the body.
3. Missing end
Every if block must close with end. Forgetting end is a common syntax error.
4. Using else if instead of elseif
Lua uses elseif (one word). else if creates a nested if that needs its own end.
Practice Questions
1. What keyword closes an if block?
end. Every if must have a matching end.
2. How do you write multi-branch conditions?
Use elseif (one word) between if and else: if a then ... elseif b then ... else ... end.
3. What is the difference between = and ==?
= assigns a value. == compares two values for equality.
FAQ
{{< faq question="Can I have multiple elseif branches?" >}} Yes, there is no limit. Lua evaluates each elseif in order and executes the first true branch. {{< /faq >}}
{{< faq question="Does Lua have a switch statement?" >}} No built-in switch. Use if-elseif chains. For many cases, consider a table lookup or function dispatch table. {{< /faq >}}
{{< faq question="How do I write a single-line if?" >}}
Lua doesn't have a single-line if. Use the and-or idiom: condition and value1 or value2 as a ternary alternative.
{{< /faq >}}
What's Next
Now learn about loops in Lua.
| Topic | Description | Link |
|---|---|---|
| Loops | while and for loops | {{< ref "18-loops" >}} |
| Functions | Defining and calling functions | {{< ref "05-functions" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro