I also couldn’t understand this for a long time, because it’s easier not to use this handful of scripts. And indeed OOP is not at all necessary, it only simplifies some aspects.
But at one point, looking at OOP in practice, I realized why this was needed.
OOP is needed in order to create objects with their built-in functions. Purely for convenience.
Let’s look at the code:
local Button = {}
Button.__index = Button
function Button.new()
local Main = {}
-- create a private value
Main._button = Instance.new("ImageButton")
-- return table as response
return setmetatable({}, Button)
end
-----------------------------------------------------------------------------------------
-- Our first function, which is responsible for pressing!
function Button:OnClick(func)
return self._button.MouseButton1Click:Connect(func)
end
-- Button:OnClick()
-- Please note that we put a colon, not a period, so that the function knows which button (table) it works with.
-----------------------------------------------------------------------------------------
-- Our second function, which is responsible for renaming!
function Button:SetName(name)
self._button.Name = name
end
return Button
This is our first script that contains OOP. This script is called a constructor.
local ButtonModule = require(script.Button)
-- We created a button!
local NewButton = ButtonModule.new()
-- Now let's rename our button!
NewButton:SetName("Shop")
-- Now let's create a function!
NewButton:OnClick(function()
print("Button Pressed!")
end)
This is our second script, here we create our button and look how quickly it happens!
We can of course write functions like this:
local function CreateButton()
return Instance.new("ImageButton")
end
local function RenameButton(Button, Name)
Button.Name = Name
end
local function OnClick(Button, Func)
return Button.MouseButton1Click:Connect(Func)
end
But will it really be easier?
Yes, it can, because everyone has a subjective idea of simplicity.
In general, what can we say?
Using OOP, we can store functions for each button separately, that is, we will not need to constantly enter which button we have in mind, self and colon solve this issue.