← Lua Academy

Typed Lua · 34 / 69

Read an optional field

YOUR TASK

Make this happen

3 steps
  1. Optional fields may be absent. Return a label using the nickname when supplied and the required name otherwise.

  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.display = function(person: { name: string, nickname: string? }): string
  return person.nickname
end

lesson.test.lua

local t = require("test")
local subject = require("cococo.subject")
t.it("missing nickname", function()
  local s = subject.load()
  t.expect(s.display({ name = "Ada" })):eq("Ada")
end)
t.it("nickname present", function()
  local s = subject.load()
  t.expect(s.display({ name = "Ada", nickname = "A" })):eq("A")
end)