Adding Methods to Shapes
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 44 of 80.
From your Lua OOP chapter you know tables can hold functions just like any other value. Shapes can describe those function fields too: turning a shape into a small contract of data and behavior.
A method field uses the function-type syntax you learned in the functions chapter. Its first parameter is conventionally named self, the table the method belongs to, and the shape can even reference itself:
type Greeter = {
name: string,
greet: (self: Greeter) -> string,
}To implement the shape, store a function in the field and give it that self parameter:
local greeter: Greeter = {
name = "Ana",
greet = function(self: Greeter): string
return `Hello, I'm {self.name}`
end,
}Calling it means passing the table as self yourself: greeter.greet(greeter). Through self the method reads the fields of whichever table it was called on.
Writing the table twice feels clumsy, and you already know Lua's cure: the colon. Next lesson connects : syntax to these typed shapes.
Challenge
EasyGive a rectangle shape a method that computes its area.
- Write
type Rectangle = {width: number, height: number, area: (self: Rectangle) -> number}. - Create
local rect: Rectanglewith width4, height6andarea = function(self: Rectangle): numberreturningself.width * self.height. - Print
rect.area(rect), thenrect.width.
Press Run Code: the output shows 24 and 4.
Try it yourself
-- 1) type Rectangle with width, height and an area method
-- 2) local rect: Rectangle (width 4, height 6) with area implemented
-- 3) print the area, then the width
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