Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create a type alias named Rectangle with:

  • width of type number
  • height of type number
  • area — a method (self: Rectangle) -> number returning width * height
  • perimeter — a method (self: Rectangle) -> number returning 2 * (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):

  1. the rectangle's area
  2. the rectangle's perimeter
  3. 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau