How to add a slash command

From ESOUI Wiki

Jump to: navigation, search

Explanation

All slash commands are stored in a global lua table called "SLASH_COMMANDS".
When the chat registers a input starting with /, it takes the text between / and the first space or the eol and looks it up in the table. If it finds an function under that string index, the function is called. If there is any text after the slash command (excluding the seperating space), that text as whole is given used as parameter for the function call. From there it can be parsed as any other input string. If no text follows the command after the slash command, a empty string ("") is used as parameter.
It is advisable to make a specialised helper function for nothing but registering in the Slash command table. That way complex parsing and switching can be done before calling the actuall function. This also allows catching exceptions and exposing them via chat (instead of the normal error dialog).
Note that despite the table taking upper case characters, the chat won't even look up a slash command containing a upper case character.

Examples

Adding a slash (chat) command is very straightforward:

function bar(extra)
  -- do something
end
 
SLASH_COMMANDS["/foo"] = bar

The above code will cause typing "/foo baz" in chat to call bar("baz") (and just plain "/foo" will call bar("")).

Anonymous functions may also be used:

SLASH_COMMANDS["/foo"] = function (extra)
  -- do something
end

If you want to give the underlying function multiple arguments, you have to parse the string that is given as to the funcion.

This example will extract any amount of space seperated parameters into a table, from where they can be processed. Using the above as an example, typing /foo baz boz would call bar("baz boz"). option[1] would hold "baz" and option[2] would hold "boz".

    local options = {}
    local searchResult = { string.match(option,"^(%S*)%s*(.-)$") }
    for i,v in pairs(searchResult) do
        if (v ~= nil and v ~= "") then
            options[i] = string.lower(v)
        end
    end

The following code segment is a simple test to see if someone either typed just /foo or /foo help allowing you to display the list of commands available.

    if #options == 0 or options[1] == "help" then
       -- Display help
    end

Notes

Personal tools
Namespaces
Variants
Actions
Menu
Wiki
Toolbox