Recap: Defining Table Shapes
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 46 of 80.
Challenge
MediumDescribe two computers, one with unknown RAM.
- Write
type Computer = {id: number, brand: string, ramInGB: number?}and annotateworkstationandlaptopasComputer. - Write
local function specs(computer: Computer): stringreturning`{computer.brand} with {computer.ramInGB} GB of RAM`when RAM is known, otherwise`{computer.brand} with unknown RAM`. - Print
specs(workstation)andspecs(laptop).
Press Run Code: the output shows Dell with 16 GB of RAM and MacBook with unknown RAM.
Try it yourself
-- 1) type Computer = {...}
local workstation = {id = 1001, brand = "Dell", ramInGB = 16}
local laptop = {id = 1002, brand = "MacBook"}
-- 2) specs(computer: Computer): string
-- 3) print specs for both
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 Maps6Typing Table Shapes
Inline Shape AnnotationsType Aliases for ShapesOptional PropertiesShapes vs. Loose TablesExtending ShapesAdding Methods to ShapesSelf and Colon MethodsRecap: Defining Table ShapesPractice on your own: Online Luau compiler