← Lua Academy

Practical scripting · 62 / 69

Handle a catchable failure

YOUR TASK

Make this happen

3 steps
  1. pcall returns a success flag and a result or error. Keep a recoverable error from escaping the function and return a deliberate fallback.

  2. Read the cases in lesson.test.lua, then choose Check solution to see what needs to change.

  3. Update subject.lua until every test passes. Keep the supplied tests unchanged.

Read the starter and tests

subject.lua

exports.safe = function(fn: () -> number): number
  return fn()
end

lesson.test.lua

local t = require("test")
local subject = require("cococo.subject")
t.it("normal result", function()
  local s = subject.load()
  t.expect(s.safe(function()
    return 7
  end)):eq(7)
end)
t.it("recoverable failure", function()
  local s = subject.load()
  t.expect(s.safe(function()
    error("missing")
  end)):eq(0)
end)