Object Oriented Programming isn’t a new concept here on the Developer Forum. People have been doing it for years. However I always found an issue with how people structure their “Classes” and “Objects”.
Here is what a template for my “Classes” look like.
--[[SERVICES]]--
--[[FOLDERS]]--
--[[MODULES]]--
--[[TYPES]]--
export type Fruit = {
--Properties
Age: number,
Cost: string,
Name: string,
--Functions
}
--[[VARIABLES]]--
local FruitClass = {}
FruitClass.__index = FruitClass
--[[FUNCTION DECLARATIONS]]--
--[[FUNCTION DEFINITIONS]]--
FruitClass.Eat = function(self: Fruit) : ()
print("This fruit has been eaten. It costed " , self.Cost)
end
FruitClass.Throwaway = function(self: Fruit) : ()
print("This fruit has been thrown away. Its age was ", self.Age , " days")
end
--[[SCRIPT]]--
local Fruit = function(Name: string, Age: number, Cost: string) : Fruit
local self = setmetatable({}, FruitClass)
--Set Properties
self.Age = Age
self.Cost = Cost
self.Name = Name
return self
end
return Fruit
This way when I want to create an object, when I required the class, the only thing returned to me is the function or the “Constructor”. It looks like this when used in another script to create a “banana”
local Fruit = require(script.Fruit)
local Banana = Fruit("Banana", 5, "$2.50")
This solves one of the main issues with the common method of OOP, where the “New” function or constructor is accessible as a method within the object itself. My method appears to be more similar to other languages with official OOP implementation where you only have access to public values
Let me know what you guys think! Is this better or worse than the common way Roblox scripters create and use “Classes” in Luau. Would you be willing to use this format?