--!strict
local RunService = game:GetService('RunService')
local Stun = {}
Stun.__index = Stun
function Stun.new(Character: Model, Level: number?, Duration: number?)
local self = setmetatable({}, Stun)
Level = Level or 1
Duration = Duration or 0.25
self.Level = Level
self.Duration = Duration
self.Connection = RunService.Heartbeat:Connect(function(DeltaTime)
print('Running')
if not self.Connection.Connected then self = nil return end
if self.Duration <= 0 then self:Remove() self = nil return end
self.Duration -= DeltaTime
end)
return self
end
function Stun:Remove()
self.Connection:Disconnect()
end
return Stun
This is the server script
local Stun = StunModule.new(Player.Character, 1, 7)
task.wait(5)
Stun:Remove()
print(Stun) -- not equal to nil
Questions
How would I make it so that when the Stun:Remove() function is called, the stun variable on the server script also gets set to nil?
How would I go about making it so if 2 stuns objects are created with the same level, the newer stun object will just override the old stun object rather than creating a separate one?
How would I be able to store these stun objects so that I can easily find whether or not the player I am looking at has stun or not.
After you close the connection with :Remove(), the Stun object should automatically be garbage collected by Lua as long as it’s not being referenced by other variable. You could simply set Stun = nil to dereference the object you created or if you want to be safe, I recommend looking into libraries such as Trove or Maid that handles object and connection removal.
Technically, you could deep copy the object but I think the best approach is just create another object and let the other one garbage collect by dereferencing. (Objects in lua are essentially tables with metadata. You would have to deep copy this table or make a new one).
The easiest way would be to create a module script and store the stun objects in a table. Or look into singleton design pattern if you want to stick with OOP.
Old post, best way to do it would be to use oop to make “stun” an object that you (can only) construct through a method of a “player” or “character” controller object.
The stun should be inserted into an array under the playercontroller object/component. Using methods of the playercontroller, you can check for the highest level of stun within the array. To make this check more efficient, you can have the array where the stuns are stored be instead a dictionary with values that are arrays for containing the stuns with the respective levels.
Like my initial (horrible) implementation, you should use tick() to expire the stuns rather then using task.delay or something to schedule the removal of the object from the array.