← Lua Academy

Typed Lua · 28 / 69

Handle a missing name

YOUR TASK

Make this happen

3 steps
  1. The type string? admits a string or nil. Narrow the value with a nil check before concatenating it. Missing and empty are different cases.

  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.label = function(name: string?): string
  return "Guest"
end

lesson.test.lua

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

t.it("missing name", function()
  local s = subject.load()
  t.expect(s.label(nil)):eq("Guest")
end)

t.it("present name", function()
  local s = subject.load()
  t.expect(s.label("Ada")):eq("Hello, Ada")
end)

t.it("empty name is still present", function()
  local s = subject.load()
  t.expect(s.label("")):eq("Hello, ")
end)