Here's an example of data isolation by generator function. The use of metatables can be tricky to comprehend, but it's easier on the system than scanning each addon's unit table. It uses a trick in which
__mode in a metatable can control whether or not the GarbageCollector can take keys and/or values out of a table when it runs. When it does take either from a table, it removes the entire entry.
This actually uses two metatables.
MasterList uses it as described above. The other is to apply our API functions to the individual tables we return to each addon in our generator function.
Lua Code:
--[[ Library Registration ]]
local LibTalentsTrack=LibStub:NewLibrary("LibTalentsTrack-1.0",1);
if not LibTalentsTrack then return; end
--[[ Internal Variables ]]
local MasterList=setmetatable({},{__mode="v"});-- Generate table with weak values to let GarbageCollection take them as necessary
--[[ Tracker Object Metatable ]]
local TrackerMeta={__index={}};
function TrackerMeta.__index:RegisterUnit(unit)
-- self is our tracker object table given to addons
if UnitExists(unit) then
local guid=UnitGUID(unit);-- Save by GUID to guarantee correct tracking
local unitdata=MasterList[guid];
if not unitdata then-- Is new unit?
unitdata={Name=UnitName(unit)};-- Populate this with default data
MasterList[guid]=userdata;-- Register table with our master list
end
self[guid]=unitdata;-- Save unit in our own list
end
end
function TrackerMeta.__index:UnregisterUnit(unit)
-- self is our tracker object table given to addons
if UnitExists(unit) then
self[UnitGUID(unit)]=nil;-- Erase our copy of the unit table (MasterList will lose its copy if this was the last reference to it next GarbageCollection cycle)
end
end
function TrackerMeta.__index:UnregisterAllUnits(unit)
-- self is our tracker object table given to addons
table.wipe(self);-- Erase everything (metatable stays intact)
end
-- Generates new tracker object for addons to use
function LibTalentsTrack:NewTracker()
return setmetatable({},TrackerMeta);
end
--[[ Tracker Stuff ]]
--[[
Do all your CLEU stuff and store all your data in the unit table at MasterList[GUID]
Be sure to check its existence every CLEU event as the GarbageCollector will randomly take it away after all other references to it are unregistered
]]
This allows addons using your lib to do this.
Lua Code:
-- Grab a new tracker object from our lib
local UnitTracker=LibStub:GetLibrary("LibTalentsTrack-1.0"):NewTracker();
local EventFrame=CreateFrame("Frame");
EventFrame:RegisterEvent("PLAYER_TARGET_CHANGED");
EventFrame:SetScript("OnEvent",function(self,event,...)
UnitTracker:RegisterUnit("target");-- Register target for tracking
end);