← Lua Academy

Functions and modules · 25 / 69

Accept behaviour as an argument

YOUR TASK

Make this happen

3 steps
  1. A function type describes a callback. Apply the provided number-to-number function twice. This lets callers choose the transformation.

  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.twice = function(value: number, transform: (number) -> number): number
  return transform(value)
end

lesson.test.lua

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

t.it("applies twice", function()
  local s = subject.load()
  t.expect(s.twice(3, function(n)
    return n + 2
  end)):eq(7)
end)

t.it("works with multiplication", function()
  local s = subject.load()
  t.expect(s.twice(3, function(n)
    return n * 2
  end)):eq(12)
end)