← Lua Academy

Typed Lua · 35 / 69

Make array absence explicit

YOUR TASK

Make this happen

3 steps
  1. Strict nil mode makes an indexed lookup optional. Handle an empty array rather than assuming the first entry exists.

  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

--!strict-nil
exports.firstOrZero = function(values: { number }): number
  return values[1]
end

lesson.test.lua

local t = require("test")
local subject = require("cococo.subject")
t.it("empty array", function()
  local s = subject.load()
  t.expect(s.firstOrZero({})):eq(0)
end)
t.it("present value", function()
  local s = subject.load()
  t.expect(s.firstOrZero({ 7 })):eq(7)
end)