Menu
CoddyTech

Recap: Typed Functions

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 31 of 80.

challenge icon

Challenge

Medium

Format a name whose middle part may be missing.

  1. Write type NameFormatter = (string, string, string?) -> string.
  2. Create local formatName: NameFormatter = function(first, last, middle) returning `{first} {middle} {last}` when middle is given, otherwise `{first} {last}`.
  3. Print formatName(firstName, lastName) when middleName == "", otherwise pass all three.

Press Run Code: with the input John, Doe and an empty line, the output shows John Doe.

Try it yourself

local firstName: string = io.read()
local lastName: string = io.read()
local middleName: string = io.read()

-- 1) type NameFormatter = (string, string, string?) -> string
-- 2) local formatName: NameFormatter = function(first, last, middle) ... end
-- 3) call it with two names when middleName is "", else with three
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler