First I’d say it’s the general setup with .new() constructor to interact with separate objects:
local module = {}
module.__index = module
function module.new()
local self = {}
self.SomeProperty = "Test"
return setmetatable(self, module)
end
function module:GetProperty(index: string)
if self[index]
return self[index]
end
end
return module
local Module = require(path.to.module)
local New = Module.new()
print(New:GetProperty("SomeProperty")) -- "Test"
That’s it for the basic object-based structure.
If you want to add a method that will execute certain code when you run the module for the first time, you can do:
- Just keep the code in the module’s body, it will execute only once on the first require, as modules cache
local module = {}
module.__index = module
function module.new()
local self = {}
self.SomeProperty = "Test"
return setmetatable(self, module)
end
function module:GetProperty(index: string)
if self[index]
return self[index]
end
end
-- example
module.PartCache = {}
for _, Part in workspace.Parts:GetChildren()
table.insert(module.PartCache)
end
--
return module
- You can make a method like :start() or .init(), but I personally prefert start()
local module = {}
module.__index = module
function module.new()
local self = {}
self.SomeProperty = "Test"
return setmetatable(self, module)
end
function module:GetProperty(index: string)
if self[index]
return self[index]
end
end
-- example
function module:start()
module.PartCache = {}
for _, Part in workspace.Parts:GetChildren()
table.insert(module.PartCache, Part)
end
end
--
return module
So whenever you initialize the module, you can call the method.
local Module = require(path.to.module)
Module:start() -- we initialize the module after requiring it
-- this way we can also call this method multiple times (if needed and applicable)
One more major approach would be making and using base classes:
Baseclass code:
local BaseClass = {}
function BaseClass:Attack()
-- perform attack code
print("Attack")
end
function BaseClass:Dodge()
-- perform dodge code
print("Dodge")
end
return BaseClass
Derived class code:
local Warrior = setmetatable({}, {__index = require(path.to.BaseClass)})
-- by defining a method that has the same name as a method from base class,
-- we are overriding it
function Warrior:Attack()
-- perform attack code
print("Overridden attack")
end
return Warrior
Now an example
local WarriorClass = require(path.to.Warrior)
WarriorClass:Attack() -- "Overridden attack"
WarriorClass:Dodge() -- "Dodge"
Our :Attack method inside Warrior class has overridden the method from base class, but as we didn’t specify a dodge method - it inherited the method from the base class.
EDIT: Hopefully there’s not going to be any typos, written all the code thru forum post editor