Methods in Lua

-- Lua supports methods defined on table types.

-- Define a rect "class"
local rect = {}
rect.__index = rect

function rect.new(width, height)
    return setmetatable({width = width, height = height}, rect)
end

-- This 'area' method is defined for the rect table.
function rect:area()
    return self.width * self.height
end

-- Methods can be defined for tables. Here's another example.
function rect:perim()
    return 2 * self.width + 2 * self.height
end

-- Main function
local function main()
    local r = rect.new(10, 5)

    -- Here we call the 2 methods defined for our table.
    print("area: ", r:area())
    print("perim:", r:perim())

    -- Lua doesn't have pointers, so there's no distinction between
    -- value and reference semantics for method calls.
    -- The following calls are equivalent to the ones above:
    print("area: ", rect.area(r))
    print("perim:", rect.perim(r))
end

main()

In Lua, we don’t have structs or explicit method definitions like in some other languages. Instead, we use tables and functions to create similar structures. Here’s how the concepts translate:

  1. We define a rect table that acts as our “class”.

  2. The new function is a constructor that creates and returns a new rect instance.

  3. Methods are defined as functions within the rect table. The : syntax in the method definition and call is syntactic sugar that automatically passes the table (object) as the first argument to the function.

  4. Lua doesn’t have a built-in concept of pointers. All tables are reference types, so there’s no need to distinguish between value and pointer receivers.

  5. We can call methods using either the colon syntax (r:area()) or the dot syntax with explicit self (rect.area(r)). Both are equivalent.

To run this program, save it as methods.lua and execute it with the Lua interpreter:

$ lua methods.lua
area:  50
perim: 30
area:  50
perim: 30

This example demonstrates how Lua can implement object-oriented concepts using its table and function features. While the syntax and exact mechanics differ from some other languages, the fundamental idea of associating data with methods that operate on that data remains the same.