Repository navigation
Foundry Commands
Part of the Foundry API reference.
New to WoW addons? Start here →
Foundry.Commands is a thin bridge over WoW's native slash command system. It gives an addon one place to register its slash commands and subcommands, with auto generated help, aliases, a guard, and clean teardown, without hiding the native primitive underneath.
This page explains the native slash system first, then why a registry helps once an addon grows past a handful of subcommands, then the Foundry.Commands API with worked examples, and finally how to migrate from AceConsole-3.0.
API version: Foundry.Commands is API version 2. Assert it with
F:RequireModule("Commands", 2)if your addon needs the module present at a minimum version. (This is the module's version; the library as a whole isF.API_VERSION.)
WoW gives every addon a global slash command system with two halves:
SLASH_MYADDON1 = "/myaddon" -- the text the player types
SLASH_MYADDON2 = "/ma" -- an alias; indices are sequential from 1
SlashCmdList["MYADDON"] = function(message, editBox)
-- message is everything the player typed after the slash word
-- editBox is the chat edit box the command came from
endTwo rules make this work:
- The
SLASH_<NAME>1,SLASH_<NAME>2, ... globals hold the slash strings, indexed sequentially starting at 1. - The
SlashCmdListkey ("MYADDON") must match the<NAME>used in those globals. WoW routes any of the registered slash strings to that one handler.
This primitive is current and is not deprecated. It is what every slash command in the game and in addons ultimately uses, including AceConsole-3.0. For a single command with no subcommands, the native primitive is the right tool and Foundry.Commands is unnecessary.
The native handler receives one raw string. An addon that wants subcommands
(/myaddon scan, /myaddon config, and so on) has to split that string, branch
on the first word, write its own help text, and keep all of that in sync by
hand. For one or two subcommands that is fine. Past roughly four, the
boilerplate starts to dominate, and three things tend to rot:
- Help drifts. The help text is maintained separately from the dispatch branches, so it falls out of date.
-
Aliases multiply branches. Every
or input == "wp"is another thing to remember in two places. -
Nothing cleans up. The handler lives in the global
SlashCmdListforever, even if the addon wants to tear it down.
Foundry.Commands keeps the native primitive underneath and adds a small registry on top: you describe each subcommand once, and the module derives dispatch, help, and aliasing from that description. This is the discoverability and verbosity argument, not a claim that the raw primitive is bad. Reach for Foundry.Commands when the registry earns its keep, and use the native primitive directly when it does not.
local F = _G.Foundry_1_0
local cmd = F.Commands:New({
name = "MyAddon",
slashes = { "/myaddon", "/ma" },
description = "MyAddon: a short one line summary.",
}):New returns a controller object that you hold. The controller owns this
addon's slash registrations. Foundry does not attach anything to your addon
object; you call methods on the controller explicitly. 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.
config fields:
| Field | Type | Required | Meaning |
|---|---|---|---|
name |
string | yes | Owner identity. Used to scope and clean up the controller and as the basis for the SlashCmdList registration. |
slashes |
array of strings | yes, at least one | The slash strings to register, with or without a leading /; each must be a single slash token (no internal whitespace, no embedded slashes). The first is canonical; the rest are aliases routed to the same handler. |
description |
string | no | One line summary printed as the first line of auto help. |
defaultHandler |
function | no | Runs when the bare slash is typed with no arguments. If absent, the bare slash prints auto help. |
guard |
function | no | A pre dispatch check. See section 6. |
printer |
function | no | How the controller prints to chat. Defaults to the default chat frame. See section 7. |
unknownMessage |
string or function | no | The message shown when no subcommand matches. It is the entire unknown-command output (the command list is not appended); include a hint like type /x help here to point users at the list. A function receives the input and returns the (e.g. localized) string; a string is printed as-is. Defaults to the English Unknown command: <input>. |
restrictionNotice |
boolean | no | Opt in to a one-line chat notice printed just before an addon restriction (combat, an encounter, a challenge mode, a PvP match, the map, or chat) activates. Off by default: a controller that does not set this gets no extra frame and no unsolicited chat output. See section 6.2. |
:New validates everything before it touches a global, and refuses on a
slash-name collision: if SlashCmdList[NAME] or any SLASH_<NAME>n global is
already set (NAME is name upper-cased), it raises in dev / prints in release and
returns nil, rather than overwriting another addon's command.
cmd:Register({
name = "scan",
args = "[full]",
help = "Scan the catalog for owned items.",
handler = function(rest) MyAddon:Scan(rest) end,
})spec fields:
| Field | Type | Required | Meaning |
|---|---|---|---|
name |
string | yes | The subcommand name, lowercased internally for matching. Names may contain spaces ("debug vertical" is a valid name distinct from "debug"). |
aliases |
array of strings | no | Alternative names routed to the same handler. Shown parenthetically in help. |
args |
string | no | A documentary hint shown in help, for example "[search]". Not parsed. |
help |
string or function | no | Help text for this subcommand. A function is called with no arguments and must return a string; this is the localization escape hatch. |
handler |
function | yes | Runs when the subcommand is invoked. Receives the remainder of the input after the matched name, with its original casing preserved. The handler parses its own arguments. |
Validation. :Register rejects bad input rather than normalizing it (dev
builds raise; release builds print and skip), so these are hard requirements:
-
name: a string, non-empty, and already trimmed (no leading or trailing whitespace; Foundry rejects rather than trimming). It must not be"help"and not"help"followed by any whitespace character, since those route to auto help at dispatch and would be unreachable. -
handler: required, and must be a function. -
aliases: if given, a table of non-empty, already-trimmed strings (no type coercion); none may be"help"or"help"followed by any whitespace character; and none may duplicate another alias in the same spec or collide with an already-registered name or alias. - A
namealready in the registry is rejected (no silent overwrite). -
:Registeron a controller that has beenDestroyed is rejected.
The handler is responsible for parsing anything after its name, including patterns another design might express as nested subcommands. Foundry.Commands keeps the registry flat in 1.0 (see section 12).
When the player invokes a registered slash, the controller runs this sequence:
-
Guard first. If a
guardis configured, it runs before anything else. If it denies, only its reason (if any) is printed and dispatch stops. Help and the registry are never reached. (Section 6.) -
Empty input. After trimming, if the input is empty, the
defaultHandlerruns if configured, otherwise auto help prints. -
helpis reserved. If the input is exactlyhelp, or begins withhelpfollowed by whitespace, auto help prints (sohelpmeis not help — it dispatches normally; the precise rule is in section 4).helpis reserved at the dispatch level, so a subcommand namedhelpcannot be registered. - Longest name wins. Otherwise the controller finds the longest registered name that is a prefix of the input and ends on a word boundary (a space or the end of the string). That subcommand's handler runs, receiving everything after the matched name as the remainder.
-
Unknown. If no registered name matches, the controller prints the
unknown-command message (your
unknownMessage, or the defaultUnknown command: <input>). The command list is not appended; put a hint liketype /x helpinunknownMessageto point users at it.
The longest-name rule is what lets multi-word names coexist as flat registrations:
cmd:Register({ name = "debug", help = "Toggle debug mode.", handler = function() MyAddon:ToggleDebug() end })
cmd:Register({ name = "debug vertical", help = "Print vertical sibling info.", handler = function() MyAddon:PrintVertical() end })-
/myaddon debugmatches"debug"(remainder empty). -
/myaddon debug verticalmatches"debug vertical"(the longer prefix). -
/myaddon debug somethingmatches"debug"with"something"as the remainder, so thedebughandler decides what to do with"something".
Auto help prints the description line (if set), a blank line, then one line
per subcommand, sorted alphabetically by name:
/myaddon scan [full] -- Scan the catalog for owned items.
/myaddon waypoint (wp) -- Clear the current map waypoint.
The [args] section is omitted when a subcommand has no args, and the help
section is omitted when it has no help. Aliases appear in parentheses after
the name. Multi-word names appear as-is in their sorted position; the registry
is flat, so they do not visually nest under a shorter prefix.
A guard runs before any other dispatch decision and decides whether the
command is allowed at all. It receives the raw input string and returns
(allowed, reason):
local dev = F.Commands:New({
name = "MyAddonDev",
slashes = { "/madev" },
guard = function(input)
if not MyAddon.devMode then
return false, "Developer mode is off."
end
return true
end,
})
dev:Register({ name = "dump", handler = function() MyAddon:Dump() end })With developer mode off, every path is blocked uniformly: /madev,
/madev dump, /madev help, and /madev anything all print
Developer mode is off. and nothing else. Because the guard runs before help,
the list of developer subcommands never leaks to a player who cannot use them.
This is the shape Sift uses for its developer command /bdev: a guard that
checks developer mode and blocks every path, help included, when it is off, so
the developer subcommands stay invisible to a normal player.
Foundry ships one guard so you do not have to write it yourself: a check against the game's own addon-restriction state.
local cmd = F.Commands:New({
name = "MyAddon",
slashes = { "/myaddon" },
guard = F.Commands.Guards.NotRestricted,
})NotRestricted checks whether the client currently reports an active addon
restriction (combat, an encounter, a challenge mode, a PvP match, the map,
or chat) and blocks the command while one is active, printing "Commands
are unavailable while <restriction> restrictions are active." On a client
new enough to expose the restriction-state API, that is exactly what it
checks. On an older client without it, NotRestricted falls back to a plain
combat-lockdown check and prints "Commands are unavailable while combat
restrictions are active." Either way, it is a drop-in guard; you do not need
to write your own combat check anymore.
NotRestricted blocks a command once a restriction is already active. If you
also want players warned a moment before that happens, opt in to
restrictionNotice on Commands:New:
local cmd = F.Commands:New({
name = "MyAddon",
slashes = { "/myaddon" },
guard = F.Commands.Guards.NotRestricted,
restrictionNotice = true,
})With restrictionNotice = true, on a client that exposes the restriction
event, the controller prints one line, "Commands are about to be paused while
<restriction> restrictions activate.", just before that restriction takes
effect. This is independent of the guard: the notice is driven by its own
setting, so a controller can opt in to the notice without using
NotRestricted at all, and using NotRestricted does not turn the notice on
by itself. Leave restrictionNotice unset (the default) and a controller
gets no extra listening frame and no unsolicited chat output.
Both messages are fixed English. Unlike unknownMessage and help, there is
no override for them; a localized addon that needs its own wording writes its
own guard instead of using NotRestricted.
By default the controller prints to the default chat frame. Supply a printer
to control formatting, for example to add an addon prefix or color:
local cmd = F.Commands:New({
name = "MyAddon",
slashes = { "/ma" },
printer = function(line) print("|cff66ccffMyAddon|r: " .. line) end,
})Auto help, the unknown-command message, and any output the controller emits go
through the printer. The unknown-command message's text is set separately
via unknownMessage (a string, or a function of the input), so it can be
localized: the printer controls how every line is emitted, unknownMessage
controls what that one line says.
Most established addons want the bare slash to do something other than print
help. Set defaultHandler:
local cmd = F.Commands:New({
name = "MyAddon",
slashes = { "/myaddon", "/ma" },
defaultHandler = function() MyAddon:OpenOptions() end, -- bare /ma opens options
})The auto-help fallback (when defaultHandler is unset) is the convenient
default for a new addon being wired up, not a behavior most shipping addons keep.
Foundry.Commands is English-only internally. To localize a subcommand's help, pass a function that returns your already-translated string:
cmd:Register({
name = "scan",
help = function() return L["Scan the catalog for owned items."] end,
handler = function() MyAddon:Scan() end,
})The function is called each time help is generated, so it always reflects the player's current locale.
The unknown-command output is exactly unknownMessage; the command list is
never appended (dispatch step 5). To send users to the list, put a hint in the
message itself:
local cmd = F.Commands:New({
name = "MyAddon",
slashes = { "/ma" },
unknownMessage = function(input)
return "Unknown command: " .. input .. ". Type /ma help for the list."
end,
})A plain string works when you do not need the input echoed back; the function form is the localization escape hatch (it receives the typed input).
When you need to do something Foundry.Commands does not wrap, drop to the raw
Blizzard surface without removing the controller. GetNativeHandles returns the
native registration this controller created:
local handles = cmd:GetNativeHandles()
-- handles.slashListKey == "MYADDON" (the SlashCmdList key)
-- handles.slashGlobals == { "SLASH_MYADDON1", "SLASH_MYADDON2" }
-- handles.handler == the function installed at SlashCmdList["MYADDON"]The returned table is a copy: rebinding handles.handler does not affect the
controller's dispatch. Mutating SlashCmdList[handles.slashListKey] directly
does affect the live registration; that is the intended escape-hatch behavior.
Use this when another addon or a Blizzard system expects to find your command in
SlashCmdList by name, or when you need to read the exact globals Foundry
registered. You own the controller and the native handles together; reaching for
the handles does not detach the controller.
cmd:Unregister("scan") -- remove one subcommand by its primary name or any alias
cmd:Destroy() -- tear down every slash registration this controller ownsDestroy releases the controller's SlashCmdList entry and SLASH_* globals so
the slash stops responding. Call it at shutdown if you want deterministic
cleanup; otherwise normal Lua object lifetime handles it. Re-registering a name
after unregistering it works.
Unregister accepts a subcommand's primary name or any of its aliases (matched
case-insensitively) and removes the whole entry, every alias included. It is a
no-op when the name is not registered.
AceConsole mixes RegisterChatCommand onto your addon object and routes to a
method you write, which then branches on the input by hand.
Before (AceConsole-3.0):
-- "AceConsole-3.0" is mixed into the addon via AceAddon's NewAddon
function MyAddon:OnInitialize()
self:RegisterChatCommand("ma", "SlashCommandHandler")
self:RegisterChatCommand("myaddon", "SlashCommandHandler")
end
function MyAddon:SlashCommandHandler(input)
input = input and input:trim():lower() or ""
if input == "" then
self:OpenOptions()
elseif input == "scan" then
self:Scan()
elseif input == "vendor" or input:match("^vendor%s+") then
self:SearchVendors(input:match("^vendor%s+(.+)$"))
elseif input == "help" then
self:PrintHelp()
else
self:Print("Unknown command: " .. input)
self:PrintHelp()
end
endAfter (Foundry.Commands):
local F = _G.Foundry_1_0
function MyAddon:OnInitialize()
local cmd = F.Commands:New({
name = "MyAddon",
slashes = { "/ma", "/myaddon" },
defaultHandler = function() self:OpenOptions() end,
})
cmd:Register({ name = "scan", help = "Scan now.", handler = function() self:Scan() end })
cmd:Register({ name = "vendor", args = "[search]", help = "Find a vendor.",
handler = function(rest) self:SearchVendors(rest ~= "" and rest or nil) end })
self.commands = cmd -- hold the controller
endWhat changed, and why it is the point:
- The bare-slash behavior is now explicit (
defaultHandler), instead of being the first branch of a hand-written chain. -
help, unknown-command handling, and auto help are provided; theelseif input == "help"branch and the manual unknown message go away. - The controller is a plain object you hold (
self.commands). The dispatch method lives on it, named where you can see it, rather than being mixed onto your addon object by a library you cannot see from the call site. - Aliases (
/ma,/myaddon) are one array entry each, not extra branches.
Multi-word commands migrate as flat registered names. Homestead's debug
family is the real example. Before, in the AceConsole handler:
elseif input == "debug" then HA:ToggleDebug()
elseif input == "debug vertical" then HA:PrintVerticalSiblings()
elseif input == "debug geography" then HA:GeographyAudit()After, as flat registrations:
cmd:Register({ name = "debug", help = "Toggle debug mode.", handler = function() HA:ToggleDebug() end })
cmd:Register({ name = "debug vertical", help = "Print vertical siblings.", handler = function() HA:PrintVerticalSiblings() end })
cmd:Register({ name = "debug geography", help = "Audit geography.", handler = function() HA:GeographyAudit() end })The longest-name dispatch rule (section 5) routes /myaddon debug vertical to
its own handler and bare /myaddon debug to the toggle.
One dispatch note worth carrying into a migration. Because matching is
longest-prefix, an input like /myaddon debug somethingelse matches debug
(the longest registered prefix) and runs the toggle with somethingelse as a
remainder the handler ignores. A pure string-equality handler would instead
have treated debug somethingelse as an unknown command. This affects only
inputs that are not real commands, so every genuine command path is preserved;
it is called out here so the behavior is not a surprise.
- It does not parse arguments into typed values. Handlers receive a raw string and parse it themselves.
- It does not provide flag parsing, argument validation, or required-argument distinctions.
- It does not persist any state. Slash registrations are runtime only; there are no SavedVariables.
- It does not localize its own output. English-only internally; localize through
consumer-supplied
helpfunctions. - It does not nest subcommands. The registry is flat in 1.0; hierarchical needs are expressed by multi-word names or by handlers parsing their own remainder.