Menu
CoddyTech

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 icon

Challenge

Easy

Give a rectangle shape a method that computes its area.

  1. Write type Rectangle = {width: number, height: number, area: (self: Rectangle) -> number}.
  2. Create local rect: Rectangle with width 4, height 6 and area = function(self: Rectangle): number returning self.width * self.height.
  3. Print rect.area(rect), then rect.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

Practice on your own: Online Luau compiler