Recap: Typed Functions
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 29 of 73.
Challenge
MediumCreate a function type alias named NameFormatter for a function that takes two required strings and an optional string?, and returns a string.
Create a function named formatName of type NameFormatter (a local annotated with the alias). It receives firstName, lastName and an optional middleName:
- When a middle name is provided, return
"[firstName] [middleName] [lastName]" - Otherwise return
"[firstName] [lastName]"
Read three input lines: the first name, the last name, and the middle name, which may be an empty line, meaning there is no middle name.
If the third line is empty (""), call formatName with only the two names; otherwise pass all three. Print the result.
Try it yourself
local firstName: string = io.read()
local lastName: string = io.read()
local middleName: string = io.read()
-- Write code here
-- type NameFormatter = (string, string, string?) -> string
-- local formatName: NameFormatter = ...
-- if middleName is "" call with two args, else with three
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 ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe '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 TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and MapsPractice on your own: Online Lua compiler