Menu
Coddy logo textTech

Self and Colon Methods

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 43 of 73.

Writing rect.area(rect) works, but you learned a better way back in Lua OOP: the colon. rect:area() is exactly the same call — Lua passes the table before the colon as the first argument, self, automatically.

The colon helps at the definition site too. function account:deposit(amount) declares a hidden first parameter named self for you:

type Account = {
    owner: string,
    balance: number,
    deposit: (self: Account, amount: number) -> (),
    getBalance: (self: Account) -> number,
}

local account = {owner = "Maya", balance = 1500}

function account:deposit(amount: number)
    self.balance += amount -- self is implicit
end

function account:getBalance(): number
    return self.balance
end

Notice how the shape declares self explicitlydeposit: (self: Account, amount: number) -> () — even though the colon hides it in the implementation. The colon is sugar; the parameter is still there, and the type spells it out. A method that returns nothing is typed with the empty return -> ().

Calling follows the same rule you already know: account:deposit(250) is identical to account.deposit(account, 250). Same runtime behavior as your OOP chapter — Luau just adds types on top.

challenge icon

Challenge

Easy

Create a type alias named Account with:

  • owner of type string
  • balance of type number
  • deposit(self: Account, amount: number) -> ()
  • getBalance(self: Account) -> number

Create a table account with owner "Maya" and balance 1500, then attach both methods using the colon definition syntax (function account:deposit(amount: number) …). deposit adds amount to the balance; getBalance returns the current balance.

Using colon calls:

  1. print the balance
  2. deposit 250
  3. print the balance again
  4. print the owner

Try it yourself

-- Write code here
-- 1) define type Account (methods take self explicitly in the type)
-- 2) create the account table, then attach deposit/getBalance with colon syntax
-- 3) print balance, deposit 250, print balance again, print owner
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