Should I / how can I apply the Janitor module to this class?

I have this class, I’m fairly new to using Janitor and I’m confused on when / if I should apply it to my constructor / deconstructor method inside of this AI Spawner class / component.

local AISpawner = {}
AISpawner.__index = AISpawner


local function _newNPC()
    local NPC = script.NPC:Clone()
    return NPC
end

function AISpawner.new()
    local self = {}
    self.instance = _newNPC()
    self.timeAlive = 0
    setmetatable(self, AISpawner)
    return self
end

function AISpawner:cleanup()
    --janitor here?
    self.instance:Destroy()
end


return AISpawner

All a janitor/maid does is compile a list of instances and connection created by an object for destruction later on.

Normally this means you need to add the janitor to both the constructor and deconstructor class like so:

local Janitor = require(--janitor)
function AISpawner.new()
    local self = {}
    self.instance = _newNPC()
self.Janitor = Janitor.new()
self.Janitor:Add(self.instance)-- mark it for destruction
    self.timeAlive = 0
    setmetatable(self, AISpawner)
    return self
end

function AISpawner:cleanup()
self.Janitor:CleanUp()
    --self.instance:Destroy()--Honestly the same thing as doing this
end

Currently your object doesn’t need a janitor as it only has one instance to manage. You will need one if the object creates multiple connections and instances during run time. (An example is my CCDIK controller creating attachments in order to locate joint positions in world space)

1 Like

So it’s essentially the same as storing connections, instances, etc. all in a table then iterating through it all to clean it up?

With that being said, and although it’s sort of off topic, what’s the best method of cleaning up my table (local self = {})? Should I just set it to nil in the deconstructor?

Yep, you can look through the source code for that.

Maid source

Notable code bits from maid
--Constructor
function Maid.new()
	return setmetatable({
		_tasks = {} - -store the tasks
	}, Maid)
end

--cleanup function
	-- Clear out tasks table completely, even if clean up tasks add more tasks to the maid
	local index, task = next(tasks)
	while task ~= nil do
		tasks[index] = nil
		if type(task) == "function" then
			task()
		elseif typeof(task) == "RBXScriptConnection" then
			task:Disconnect()
		elseif task.Destroy then
			task:Destroy()
		end
		index, task = next(tasks)
	end

Janitor should have a different method that is faster according to the benchmarking done.

Unfortunately, I used to think this does something but it doesn’t.

All it does is remove the local reference to the table in the cleanup function enviroment.

For best practice set the object to nil like the destroy documentation, though it’s unnecessary as lua will detect the table is not being used anymore and eventually garbage collect it.

local part = Instance.new("Part")
part:Destroy()
part = nil