- This topic is empty.
-
AuthorPosts
-
June 26, 2026 at 1:08 am #7049
Many beginners quickly learn that the
returnstatement sends a value back from a function. However, one confusing situation occurs when a program seems to stop before reaching the next line of code.A common question is:
“Why doesn’t my
print()statement execute afterreturn?”The answer lies in understanding what
returnactually does.The Code
function fact(n) if n == 0 then return 1 else return fact(n - 1) * n end end print("Enter number:") a = io.read("*n") return fact(a) print(fact(a))The Error
Running the program produces an error similar to:
<eof> expected near 'print'At first glance, it looks like there is something wrong with the
print()statement.In reality, the problem is the
returnstatement immediately before it.What Does
returnDo?When Lua encounters a
returnstatement, it immediately:- Stops executing the current function or file.
- Returns the specified value.
- Ignores every statement that comes after it.
Think of
returnas an exit door.Once your program walks through that door, it never comes back to execute the remaining lines.
For example:
print("Start") return 10 print("End")The second
print()can never run because execution has already ended.Why Does This Happen?
Consider these lines:
return fact(a) print(fact(a))Execution proceeds as follows:
- Calculate
fact(a). - Return the value.
- End the program.
- Never reach
print(fact(a)).
The
print()statement is therefore unreachable.The Correct Solution
If your goal is simply to display the factorial, remove the
returnstatement.function fact(n) if n == 0 then return 1 else return fact(n - 1) * n end end print("Enter number:") local a = io.read("*n") print(fact(a))Now the program:
- Asks for a number.
- Calculates the factorial.
- Prints the result.
Example:
Enter number: 5 120When Should You Use
return?Use
returnwhen you want to send a value back from a function.Example:
function square(x) return x * x end print(square(4))Output:
16Here,
returnis inside the function, which is exactly where it belongs.Can
returnBe Used Outside a Function?Yes—but only when it is the last statement in a Lua file.
This is mainly done when creating modules that return a table or a value to another script.
For normal beginner programs, you usually do not need a
returnat the end of the file.Beginner Tips
- Use
returnto send a value back from a function. - Code after a
returnstatement is never executed. - If you only want to display a result, use
print()instead ofreturn. - Prefer
localvariables whenever possible.
Key Takeaway
returndoes much more than return a value—it also ends execution of the current function or file. Once Lua encounters areturn, every line after it becomes unreachable. Understanding this behavior will help you avoid many confusing errors as you continue learning Lua. -
AuthorPosts
- You must be logged in to reply to this topic.
