← Lua Academy

Thinking in Lua · 9 / 69

Reject invalid quantities

YOUR TASK

Make this happen

3 steps
  1. An early return handles an exceptional case before the main calculation. Return zero for negative quantities; otherwise multiply by the price.

  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.cost = function(qty: number, price: number): number
  return qty * price
end

lesson.test.lua

local t = require("test")
local subject = require("cococo.subject")

t.it("rejects negative", function()
  local s = subject.load()
  t.expect(s.cost(-2, 10)):eq(0)
end)

t.it("normal quantity", function()
  local s = subject.load()
  t.expect(s.cost(3, 10)):eq(30)
end)