I’m trying to redo my current project since it uses Tool instances and it’s kinda holding me back from expanding in the way I would like to. I’m new to OOP and have a general idea of how it works, same with psuedotools, but I need a push in the right direction. Any help?
I was thinking I could do something like this in a module script:
local Weapons= {}
Weapons.__index = Weapons
function Weapons.new(name, enabled, damage, spread, firerate, reloadtime, auto, sound)
local newGun = {}
setmetatable(newGun, Weapons)
newGun.Name = name
newGun.Enabled = enabled
newGun.Damage = damage
newGun.Spread = spread
newGun.Firerate = firerate
newGun.Reloadtime = reloadtime
newGun.Auto = auto
newGun.Sound = sound
return newGun
end
Then having a local script create all the gun instances like this:
Well in OOP generally for a constructor you would want it to have the bare minimum amount of parameters in order to well construct it easier which is what you are having issues with. To do this we can use to borrow some ideas from Instances for example having predetermined settings like
--By default it's false
newGun.Enabled = false
Then we can just enable it later like we do with instances:
local gun = Weapons.new()
gun.Enabled = true
Otherwise, we can also use dictionaries or tables similar to raycast parameters in order to organize the settings easier.
local gunSettings = {
damage = 50;
headshot = 100;
rpm = 700;
magCapacity = 30;
velocity = 1500;
range = 5000;
}
function Weapons.new(gunSettings)
local newGun = {}
setmetatable(newGun, Weapons)
newGun.Settings = gunSettings
return newGun
end
Yeah, these are the possible ways of organizing a constructor for pseudo-OOP purposes in Roblox.
I don’t agree with the idea of falling into the OOP trap, as OOP generally doesn’t scale very well and just creates coding/conceptual overhead. However, what you’re really asking about is default parameters which isn’t necessarily OOP. If you’re intent on doing OOP, you can use it just the same, but this is about function parameters, which applies to more than just constructors.
function getNewWeapon(name, enabled, damage, spread, firerate, reloadtime, auto, sound)
--code to clone/spawn new weapon
newGun.Name = name or "SimpleGun"
newGun.Enabled = enabled or false
newGun.Damage = damage or 5
newGun.Spread = spread or 0
newGun.Firerate = firerate or 2
newGun.Reloadtime = reloadtime or 10
newGun.Auto = auto or false
newGun.Sound = sound or nil
return newGun
end