← Lua Academy

Practical scripting · 63 / 69

Separate validation and calculation

YOUR TASK

Make this happen

3 steps
  1. Keep validation at the boundary and calculation inside it. Reject negative width or height; otherwise compute area, including a zero-area shape.

  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.area = function(w: number, h: number): number
  return w * h
end

lesson.test.lua

local t = require("test")
local subject = require("cococo.subject")
t.it("rejects negative width", function()
  local s = subject.load()
  t.expect(function()
    s.area(-2, 3)
  end):raises()
end)
t.it("rejects negative height", function()
  local s = subject.load()
  t.expect(function()
    s.area(2, -3)
  end):raises()
end)
t.it("zero is valid", function()
  local s = subject.load()
  t.expect(s.area(0, 3)):eq(0)
end)
t.it("positive area", function()
  local s = subject.load()
  t.expect(s.area(2, 3)):eq(6)
end)