Adding Methods to Shapes
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 42 of 73.
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
EasyCreate a type alias named Rectangle with:
widthof typenumberheightof typenumberarea— a method(self: Rectangle) -> numberreturningwidth * heightperimeter— a method(self: Rectangle) -> numberreturning2 * (width + height)
Create a variable rect of type Rectangle with width 4, height 6, and both methods implemented (remember the self parameter).
Print, each on its own line (call the methods with dot syntax, passing rect as self):
- the rectangle's area
- the rectangle's perimeter
- the rectangle's width
Try it yourself
-- Write code here
-- 1) define type Rectangle with two number fields and two methods
-- 2) create rect (width 4, height 6) implementing both methods
-- 3) print area, perimeter and width
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 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