Quantcast

Add an addon:Defer() function for deferral

James Whitehead II [11-22-10 - 19:10]
Add an addon:Defer() function for deferral

This function will defer the execution of a method or function until the
player as exited combat.
Filename
AddonCore.lua
diff --git a/AddonCore.lua b/AddonCore.lua
index 6722720..d524340 100644
--- a/AddonCore.lua
+++ b/AddonCore.lua
@@ -127,6 +127,49 @@ addon:RegisterEvent("ADDON_LOADED", function(event, ...)
 end)

 --[[-------------------------------------------------------------------------
+--  Support for deferred execution (when in-combat)
+-------------------------------------------------------------------------]]--
+
+local deferframe = CreateFrame("Frame")
+deferframe.queue = {}
+
+local function runDeferred(thing)
+    local thing_t = type(thing)
+    if thing_t == "string" and addon[thing] then
+        addon[thing](addon)
+    elseif thing_t == "function" then
+        thing(addon)
+    end
+end
+
+-- This method will defer the execution of a method or function until the
+-- player has exited combat. If they are already out of combat, it will
+-- execute the function immediately.
+function addon:Defer(...)
+    for i = 1, select("#", ...) do
+        local thing = select(i, ...)
+        local thing_t = type(thing)
+        if thing_t == "string" or thing_t == "function" then
+            if InCombatLockdown() then
+                deferframe.queue[#deferframe.queue + 1] = select(i, ...)
+            else
+                runDeferred(thing)
+            end
+        else
+            error("Invalid object passed to 'Defer'")
+        end
+    end
+end
+
+deferframe:RegisterEvent("PLAYER_REGEN_ENABLED")
+deferframe:SetScript("OnEvent", function(self, event, ...)
+    for idx, thing in ipairs(deferframe.queue) do
+        runDeferred(thing)
+    end
+    table.wipe(deferframe.queue)
+end)
+
+--[[-------------------------------------------------------------------------
 --  Localization
 -------------------------------------------------------------------------]]--