Recap - Safe Division
Part of the Logic & Flow section of Coddy's Lua journey — lesson 34 of 54.
Challenge
EasyWrite a function safeDivide that takes a and b and returns the result of dividing a by b, or an error message if the division fails.
The function should use pcall() to safely perform the division operation. Create an inner function that performs the division and raises an error if b is zero, then wrap it with pcall() to catch any errors.
Logic:
- Create an inner function that checks if
bis 0 - If
bis 0, callerror("Cannot divide by zero") - Otherwise, return
a / b - Use
pcall()to execute the inner function - If successful, return
"Result: "followed by the division result - If an error occurs, return
"Error: "followed by the error message
Parameters:
a(number): The dividendb(number): The divisor
Returns: A string containing either "Result: " followed by the division result, or "Error: " followed by the error message (string)
Try it yourself
function safeDivide(a, b)
-- Write code here
end
All lessons in Logic & Flow
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board