← Lua Academy

Thinking in Lua · 11 / 69

Default only when missing

YOUR TASK

Make this happen

3 steps
  1. The or operator is useful for defaults, but it replaces false as well as nil. Preserve an explicit false preference and default only nil to true.

  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.enabled = function(value: boolean?): boolean
  return value or true
end

lesson.test.lua

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

t.it("default enabled", function()
  local s = subject.load()
  t.expect(s.enabled(nil)):eq(true)
end)

t.it("explicit opt out", function()
  local s = subject.load()
  t.expect(s.enabled(false)):eq(false)
end)

t.it("explicit opt in", function()
  local s = subject.load()
  t.expect(s.enabled(true)):eq(true)
end)