Menu
Coddy logo textTech

Recap - Safe Division

Part of the Logic & Flow section of Coddy's Lua journey — lesson 34 of 54.

challenge icon

Challenge

Easy

Write 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 b is 0
  • If b is 0, call error("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 dividend
  • b (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