Metatables and metamethods

Hello, I use the oriented object a lot recently and I wanted to know how to use metatables but in a certain way that you can do this with:

local module = require(path.to.module)
local newUI = module.new()
local container = newUI:CreateContainer()
local button = container:CreateButton()

as you can see, I can insert a button in the variable container and not in the variable newUI. If you could give me an example because I already searched on the forum and the documentation.

So in this example newUI:CreateContainer() would return a metatable object with the method CreateButton.

This concept is known as a design pattern called the builder pattern. Essentially we create an object that allows us to chain calls to add onto the object on runtime.

Code to do that is as follows:

Module


-- Create a new UI object
local UI = {}
UI.__index = UI

function UI.new()
    local self = setmetatable({}, UI)
    self.containers = {}
    return self
end

-- Create a new container and add it to the UI
function UI:CreateContainer()
    local container = { buttons = {} }
    setmetatable(container, { __index = self })
    table.insert(self.containers, container)
    return container
end

-- Create a new button and add it to the container
function UI:CreateButton()
    local button = {}
    setmetatable(button, { __index = self })
    table.insert(self.buttons, button)
    return button
end

return UI

Usage:

local newUI = module.new()

-- Create a new container and add it to the UI
local container = newUI:CreateContainer()

-- Create a new button and add it to the container
local button1 = container:CreateButton()
local button2 = container:CreateButton()

-- You can also create another container with buttons
local container2 = newUI:CreateContainer()
local button3 = container2:CreateButton()
2 Likes