Skip to content

Foundry Lifecycle

R edited this page Sep 27, 2026 · 5 revisions

Foundry.Lifecycle

Part of the Foundry API reference.

New to WoW addons? Start here →

Foundry.Lifecycle creates your addon object and runs your startup code at the right moments. It is the replacement for AceAddon-3.0's addon object plus its OnInitialize/OnEnable callbacks: instead of mixing methods onto a table a library hands you, you keep your own addon table and subscribe to the WoW startup and pre-unload signals (addon loaded, player login, player logout, and, where the client exposes it, the pre-unload signal that runs right before SavedVariables are written) through a small controller you hold.

This page explains the native startup signals first, then why a controller helps once an addon needs to coordinate them, then the Foundry.Lifecycle API with worked examples, and finally how to migrate from AceAddon-3.0.

API version: Foundry.Lifecycle is API version 4. Assert it with F:RequireModule("Lifecycle", 4) if your addon needs the module present at a minimum version. (This is the module's version; the library as a whole is F.API_VERSION.)


1. Startup in WoW: the native signals

When your addon loads and a character logs in, the game fires a fixed sequence of events. Three of them mark the phases almost every addon cares about:

local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")    -- fires once per addon, when its files + SavedVariables are loaded
f:RegisterEvent("PLAYER_LOGIN")    -- fires once, after all addons are loaded and the world is about to show
f:RegisterEvent("PLAYER_LOGOUT")   -- fires once, as the player leaves the world

f:SetScript("OnEvent", function(_, event, loadedName)
    if event == "ADDON_LOADED" and loadedName == "MyAddon" then
        -- my SavedVariables exist now
    elseif event == "PLAYER_LOGIN" then
        -- safe to read the game world and build UI
    elseif event == "PLAYER_LOGOUT" then
        -- last chance to write SavedVariables
    end
end)

Two things make this work, and two things make it tedious:

  • ADDON_LOADED fires for every addon, so your handler has to filter on the name payload to find your own load.
  • The order matters. ADDON_LOADED for your addon comes before PLAYER_LOGIN; reading the game world too early (in ADDON_LOADED) gets you incomplete data.

These are current, non-deprecated events; they are what every startup path in the game ultimately uses, including AceAddon-3.0. For a single addon that just needs "do this once at login," one frame and one RegisterEvent is the right tool and Foundry.Lifecycle is unnecessary.


2. Why a controller, and when

The native signals are raw. An addon that wants clean startup has to: create a frame, register three events, filter ADDON_LOADED by its own name, branch on the event in one handler, and remember that some of its code must wait for login rather than load. AceAddon-3.0 packages this for you, but in exchange it creates your addon object, mixes its own methods onto it, and calls your callbacks from inside machinery you cannot see from the call site.

Foundry.Lifecycle keeps the native signals underneath and adds a small controller on top. You describe what should run at each phase once, as plain handlers, and the controller takes care of the frame, the name filtering, and the event branching. Crucially:

  • It adopts your existing addon table. It does not create a new object for you and it never writes anything into the table you give it.
  • It is honest about what each hook means. The hooks are named for the raw signals they bridge (addon loaded, login, logout, and pre-unload) and promise nothing beyond that signal having happened; addon-loaded and login can fire later than their native event if the character's identity was not yet resolved when it fired (see section 4).

Reach for Foundry.Lifecycle when an addon has real startup structure to coordinate, and use the native signals directly when it does not.


3. Creating a controller: F.Lifecycle:New(owner, addonName)

local F = _G.Foundry_1_0

MyAddon = MyAddon or {}                       -- your own addon table
local lifecycle = F.Lifecycle:New(MyAddon, "MyAddon")

:New returns a controller object that you hold. The controller owns this addon's startup subscriptions. Foundry favors composition by reference (you hold the controller and call its methods) over mixing methods onto your addon object the way some libraries do.

:New takes two arguments:

Argument Type Required Meaning
owner table no (see below) Your existing addon table. This is the primary form: pass the table you already hang your addon on, and Foundry adopts it. Each phase hook is called with this exact table, so method-style handlers (function(self) … end) bind correctly.
addonName string yes The TOC addon name. Foundry uses it to match the ADDON_LOADED signal to this controller, and as the identity that owns this controller (see section 9).

Adopt, don't pollute. The owner table is yours. Foundry reads its identity to pass it back to your hooks, but it never writes a single key into it: no status fields, no methods, no bookkeeping. The table you pass to :New has the exact same keys afterward as before, and that stays true through every phase. (This is a deliberate departure from libraries that decorate the object they manage.)

Fresh-object form (secondary). If you have no table of your own to adopt, omit owner (or pass nil) and the controller manages a plain object on your behalf. Most addons have a table already and use the primary adopt form.

The shared machinery behind every controller is designed to stay efficient no matter how many addons use it: adding the hundredth consumer costs the same as adding the first.


4. The four phase hooks

A controller exposes one hook per signal. Each is one-shot: it fires exactly once, then never again.

local lifecycle = F.Lifecycle:New(MyAddon, "MyAddon")

lifecycle:OnAddonLoaded(function(self)
    -- self == MyAddon; SavedVariables for "MyAddon" are loaded now
    self.db = self.db or {}
end)

lifecycle:OnLogin(function(self)
    -- self == MyAddon; safe to read the world and build UI
    self:BuildUI()
end)

lifecycle:OnUnloading(function(self, closingClient)
    -- self == MyAddon; runs just before SavedVariables are written
    self:FlushBeforeUnload(closingClient)
end)

lifecycle:OnLogout(function(self)
    -- self == MyAddon; last chance to persist state
    self:Flush()
end)
Method Fires when
:OnAddonLoaded(handler) The game has loaded this addon's files and SavedVariables (the ADDON_LOADED signal for addonName). Use it for anything that needs your saved data but not the game world.
:OnLogin(handler) The player has logged in and the world is available (the PLAYER_LOGIN signal). Use it for UI construction and anything that reads game state.
:OnUnloading(handler) The client is about to unload every addon, before SavedVariables are written (the ADDONS_UNLOADING signal, on clients that expose it). Use it for last-moment work that has to happen before the save. See 4.1 for the details.
:OnLogout(handler) The player is leaving the world (the PLAYER_LOGOUT signal). Use it to persist anything not already saved.

Handler signature. Each handler is called as handler(owner): your adopted table is passed straight back, so a method-form handler receives it as self, the same way AceAddon's OnInitialize/OnEnable receive self. The underlying frame is never passed to you, and the raw event payloads are not forwarded; if you need them, register the native event yourself (or use Foundry.Events). :OnUnloading is the one exception: its handler receives a second argument, handler(owner, closingClient) (see 4.1).

One hook per phase. Registering a second handler for a phase that already has one is a developer error: it is rejected loudly rather than silently replacing or stacking the first. One controller means one addon-loaded handler, one login handler, one unloading handler, one logout handler.

The one-hook rule holds for the controller's whole life. Registering a second handler for a phase is rejected even after that phase has already fired. Running a hook does not re-open its slot. (Registering a hook for the first time after its signal has passed is a different thing and is fine: a first :OnLogin registered after login fires immediately via catch-up, section 5. That is a first registration, not a second.)

4.1 OnUnloading: the pre-unload signal

ADDONS_UNLOADING is the game's signal that every addon is about to be torn down and its SavedVariables written to disk. It exists on clients recent enough to expose it; older clients do not fire it at all, and :OnUnloading degrades gracefully there (see below).

What closingClient tells you. The handler's second argument is a boolean. It is true when the whole game client is exiting (the player is quitting the application), and false when the session is merely ending. closingClient distinguishes a full client exit from every other unload. It does not tell you which kind of unload you are in, so do not use it to tell a /reload from an ordinary logout.

Handlers run in registration order. This is different from :OnLogin and :OnLogout, where Lifecycle makes no promise about the order two different addons' handlers run. Unloading handlers fire in the order their controllers registered :OnUnloading, first registered, first run.

One hook per controller. Exactly like the other three phases, registering a second :OnUnloading handler on the same controller is rejected as a developer error naming the addon and stating the one-hook-per-phase rule, and the first handler is left in place.

Availability. :OnUnloading can be registered on any client. On one that does not expose a valid ADDONS_UNLOADING event, registration still succeeds, but the hook simply never fires; no error is raised, because there is no signal to hook. There is no supported way to ask in advance whether this client will ever fire ADDONS_UNLOADING; write your handler so that not firing is a safe outcome, the same way you would for any optional signal.

No ordering against OnLogout. Lifecycle makes no promise about whether OnUnloading fires before, after, or interleaved with OnLogout across addons. Treat them as two independent signals that both happen to occur at the end of a session; do not build logic that depends on one having already run relative to the other.

No catch-up. Unlike :OnLogin, there is no "already happened" case to catch up to: ADDONS_UNLOADING only ever fires once, live, at the real end of a session, so registering :OnUnloading always means waiting for that live signal.

Destroyed controllers. Calling :OnUnloading on a controller that has already been Destroyed is refused, the same as every other method (section 8). Calling Destroy on a controller that already registered :OnUnloading removes it from the pending list, so a destroyed controller's unloading handler will not fire even if the client later reports ADDONS_UNLOADING (section 8).

Why there is no "ready" hook (yet)

These four hooks are raw signals and nothing more. :OnAddonLoaded means "your addon's ADDON_LOADED fired and the character's name and realm are known" (see "Addon-loaded can wait for the character's identity" below); it does not promise that a settings store has been created, defaults filled in, or migrations run. That richer "everything is initialized and ready" guarantee is a real thing addons want, but it cannot honestly exist until Foundry ships the database layer that provides it. Naming a hook ready today would be a name that implies a guarantee Foundry does not yet carry, so it is deliberately absent. When the database module lands, a guaranteed-ready hook layers on top of these signals, and these four stay exactly what they say they are.

Addon-loaded can wait for the character's identity

On some clients, ADDON_LOADED (and even PLAYER_ENTERING_WORLD) can fire before the client has resolved the player's own name and realm; a fresh client session can log in with that identity still unresolved for a moment. On a client with region-wide unique names (where RegionalUniqueNamesEnabled() is true, for example WoW Forever), the identity Lifecycle waits for also includes the character's surname, and the same hold covers a surname that has not arrived yet. :OnAddonLoaded fires at the real ADDON_LOADED when identity is already known there, which is the case on a normal login or a /reload. When it is not, Lifecycle holds your handler rather than firing it over a placeholder name, and releases it once the name and realm resolve (after combat ends, if you log in mid-fight), always before :OnLogin. A newly-loaded addon that arrives while another is still waiting joins the wait too, so none of them runs ahead of an addon already waiting. You do not opt into this: it is automatic, and wherever identity is already resolved at ADDON_LOADED, nothing is held, no extra events are registered, and no timer runs.

That surname wait is capped, not open-ended. If a character is reported without a surname, the hold releases anyway once about a second has passed since the character entered the world or your addon loaded, whichever is later, even if no surname has arrived by then (if the player is in combat at that point, the release still waits for combat to end). Your handler then runs with the character identified by first name alone. See the Foundry.DB reference for what that means for the character's saved-data key.

If the session ends while your addon is still held (the player logs out before the name and realm ever resolve), your :OnUnloading and :OnLogout handlers do not run either: your addon-loaded and login handlers never ran, so there is nothing to wind down.


5. Catch-up: registering a hook after its signal already fired

A controller can be created at any point in startup: before your SavedVariables have loaded, after they have loaded, or even after PLAYER_LOGIN has already happened (common for load-on-demand addons). Each phase does the right thing no matter when you register, and the two phases differ deliberately in how they treat a signal that is already in the past:

  • Register before the signal, and you wait for it. If you register a hook before its signal has fired, nothing special happens: the controller simply holds your handler and runs it when the live signal arrives, exactly as if you had registered it the conventional early way. Early registration is the normal, safe case: :OnAddonLoaded and :OnLogin registered up front fire on the real ADDON_LOADED and PLAYER_LOGIN when they come.
  • Login catches up. If you register :OnLogin after PLAYER_LOGIN has already fired, your handler runs immediately, right then. You never miss login by being late. (This is the honest replacement for the old "wait a second and retry" pattern some addons hand-roll: there is nothing to retry, because a late registration catches up on its own.) Login can also wait: if PLAYER_LOGIN fires while your addon-loaded phase is still held for the character's identity (see the note above), your login handler waits too, and both fire together once identity resolves.
  • A missed addon-loaded does NOT replay. ADDON_LOADED is a single moment in the past. If you register :OnAddonLoaded for an addon that is already loaded, the catch-up still fires your handler (your saved data exists, so there is something true to act on). But if you genuinely missed the live signal and the addon was not loaded at registration time, it is not re-synthesized; there is no stale event to replay.

The practical rule: register before the signal and you wait for it; register after it and login is a state you can always catch up to, while addon-loaded is a moment you either observe live or observe as already past.

Timing note. A catch-up hook runs synchronously, right inside the registration call. If you register :OnLogin after login has already fired, your handler has run by the time :OnLogin returns; the same holds for :OnAddonLoaded against an already-loaded addon. The hook fires once, at or after its signal, never before. The one exception is the character-identity hold above: an already-loaded addon whose identity is not yet resolved still waits, and its catch-up fires later, when identity resolves, rather than synchronously inside the registration call.


6. Error behavior

Many addons can share the same underlying startup machinery, so one addon's bad handler must never harm another's. Foundry.Lifecycle guarantees:

  • One hook's error never stops the others. If your login handler throws, every other addon's login handler still runs. The failure of one phase handler does not starve the rest; the full set of handlers for a signal is always attempted.
  • The failure is always surfaced. An error is never swallowed. In a release build it is reported (printed) rather than raised, so a single broken addon cannot take down login for everyone. In a development build it is raised loudly so you see it, but after all handlers for that signal have run, not at the throw site. This is intentional: surfacing at the throw site would abort the run and starve the handlers that had not gone yet, which is exactly the outcome the continue-on-error guarantee exists to prevent.

So in development, expect a thrown error to appear after the rest of that phase's work has completed, not in the middle of it. That ordering is the price of keeping every addon's startup independent, and it is deliberate.


7. The escape hatch: controller:GetNativeHandles()

When you need to do something Foundry.Lifecycle does not wrap, drop to the raw surface without removing the controller. GetNativeHandles returns the live startup frame plus a detached snapshot copy of this controller's registered hooks:

local handles = lifecycle:GetNativeHandles()
-- handles.frame  == the live frame the startup signals are registered on
-- handles.hooks  == a detached copy of { addonLoaded = fn?, login = fn?, logout = fn? } (mutating it does not affect dispatch)

The hooks table is a shallow copy: reading it tells you which phases you have registered, but mutating it cannot change what the controller dispatches. The frame is the real, shared startup frame; treat it as read-only inspection, not something to re-script. Use this when another system needs to find the underlying frame, or when you want to confirm which hooks a controller holds.


8. Tearing down: controller:Destroy()

lifecycle:Destroy()   -- opt this owner out of all remaining phases

Destroy unsubscribes the owner from every remaining phase and releases the controller's references. After Destroy:

  • A pending addon-loaded, login, unloading, or logout for this owner will not fire.
  • The owner's addonName is released, so a later :New for that name is allowed again (see section 9).
  • Every method on the destroyed controller fails loudly in a development build and refuses with a printed message in a release build. Calling Destroy twice refuses.

Destroy does not fire the logout or unloading hooks. Logout and pre-unload are game signals: the session ending. Destroy is deliberate teardown you initiated. Opting out includes opting out of both: if you want logout or pre-unload cleanup to run, let the game fire it; do not expect Destroy to stand in for either.

The shared startup frame is library state and is never torn down by a single controller's Destroy; it stays alive for the session and simply stops tracking the owner you destroyed.


9. One controller per addon name

A given addonName may own exactly one live Lifecycle controller at a time. Calling :New again with a name that already owns a live controller is rejected as a developer error, and the first controller is left untouched; Foundry refuses the operation rather than silently replacing your working registration.

This rejection holds for the controller's whole life, including after its addon-loaded hook has already fired; being past the load moment does not free the name. The only thing that frees a name is Destroy (section 8); after that, a fresh :New for the same name is permitted.


10. Migrating from AceAddon-3.0

AceAddon creates your addon object with NewAddon, mixes its methods onto it, and calls OnInitialize (at load) and OnEnable (at login) for you. Lifecycle keeps your object as your own and subscribes the same two phases as explicit hooks.

The mapping is direct:

AceAddon-3.0 Foundry.Lifecycle
LibStub("AceAddon-3.0"):NewAddon("MyAddon") F.Lifecycle:New(MyAddon, "MyAddon") (adopts your existing table)
function MyAddon:OnInitialize() (runs at load) lifecycle:OnAddonLoaded(function(self) … end)
function MyAddon:OnEnable() (runs at login) lifecycle:OnLogin(function(self) … end)

Before (AceAddon-3.0):

-- AceAddon creates and owns the MyAddon object
MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")

function MyAddon:OnInitialize()
    -- runs once, at ADDON_LOADED; saved data is available
    self.db = LibStub("AceDB-3.0"):New("MyAddonDB")
end

function MyAddon:OnEnable()
    -- runs once, at PLAYER_LOGIN; the world is available
    self:RegisterEvents()
    self:BuildUI()
end

After (Foundry.Lifecycle):

local F = _G.Foundry_1_0

MyAddon = MyAddon or {}                        -- your table, your object
local lifecycle = F.Lifecycle:New(MyAddon, "MyAddon")

lifecycle:OnAddonLoaded(function(self)
    -- runs once, at ADDON_LOADED; saved data is available
    self.db = LibStub("AceDB-3.0"):New("MyAddonDB")
end)

lifecycle:OnLogin(function(self)
    -- runs once, at PLAYER_LOGIN; the world is available
    self:RegisterEvents()
    self:BuildUI()
end)

MyAddon.lifecycle = lifecycle                   -- hold the controller

What changed, and why it is the point:

  • You keep your object. MyAddon is a plain table you declare; Foundry adopts it and never decorates it. There is no library-owned object identity to reason about, and nothing mixed onto your table that you did not put there.
  • The phases are explicit. OnInitialize and OnEnable were methods a library called by convention; now they are named hooks you register at a call site you can see. The handler still receives self, so the bodies move over unchanged.
  • The controller is a plain object you hold (MyAddon.lifecycle), the same way Foundry.Commands hands you a controller rather than mixing methods onto your addon.

OnInitialize/OnEnable map cleanly because they are the addon-loaded and login signals under the hood. There is no OnDisable equivalent: Lifecycle does not provide a manual enable/disable trigger of its own. If your addon relied on AceAddon's runtime :Disable()/:Enable(), that is a behavior you implement yourself now (or retire deliberately); Lifecycle does not pretend to offer it. For logout-time persistence, use :OnLogout, which AceAddon had no direct equivalent for.


11. What Foundry.Lifecycle does not do

  • No "ready" hook. The four hooks are raw signals (addon-loaded additionally waits for the character's identity, section 4). A settings/database-ready guarantee is a future addition once the database layer exists (section 4).
  • No ordering between addons. Lifecycle promises nothing about the order two different addons' login or logout hooks run. If your own modules need to be ordered, keep orchestrating them yourself inside your hook. Unloading is the one exception: unloading handlers run in registration order (section 4.1).
  • No ordering between OnUnloading and OnLogout. The two are independent signals; Lifecycle does not promise which fires first (section 4.1).
  • No manual disable/enable. It provides no AceAddon-style runtime :Disable()/:Enable() trigger. Subscribing to logout is for session-end persistence, not a stand-in for manual disable.
  • No dependency management. The only "missing dependency" it cares about is Foundry itself, which your addon already guards for at the _G.Foundry_1_0 bootstrap. It does not check or order your other libraries.
  • No persisted state. Controllers are runtime only; there are no SavedVariables.
  • No player-facing text. Its only output is developer diagnostics when you misuse the API.
  • It never writes into your owner table. Adoption is read-only; the table you pass to :New is never mutated (section 3).

By BawrLabs.

Clone this wiki locally