Recap: Typed Functions
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 31 of 80.
Challenge
MediumFormat a name whose middle part may be missing.
- Write
type NameFormatter = (string, string, string?) -> string. - Create
local formatName: NameFormatter = function(first, last, middle)returning`{first} {middle} {last}`whenmiddleis given, otherwise`{first} {last}`. - Print
formatName(firstName, lastName)whenmiddleName == "", 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler