Recap: Defining Table Shapes
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 44 of 73.
Challenge
MediumCreate a type alias named Computer with:
idof typenumberbrandof typestringramInGBof typenumber?(optional)boot— a method(self: Computer) -> ()
Create two computers (attach boot with the colon definition syntax):
workstation— id1001, brand"Dell", ramInGB16; itsbootprints[brand] is booting up...laptop— id1002, brand"MacBook", no ramInGB; itsbootprints[brand] is starting...
Create a function specs that takes a Computer and returns a string: [brand] with [ramInGB] GB of RAM when RAM is known, otherwise [brand] with unknown RAM.
Then, in order:
- call
workstation:boot() - call
laptop:boot() - print
specs(workstation) - print
specs(laptop) - print the id of
workstation
Try it yourself
-- Write code here
-- 1) define type Computer (optional ramInGB, boot method)
-- 2) create workstation and laptop, attach boot with colon syntax
-- 3) write specs with a nil check on ramInGB
-- 4) boot both, print both specs, print workstation.id
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 Maps6Typing Table Shapes
Inline Shape AnnotationsType Aliases for ShapesOptional PropertiesShapes vs. Loose TablesExtending ShapesAdding Methods to ShapesSelf and Colon MethodsRecap: Defining Table Shapes