forked from Bastion/Bastion
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.4 KiB
71 lines
1.4 KiB
-- Create a wow command handler class
|
|
---@class Command
|
|
local Command = {}
|
|
Command.__index = Command
|
|
|
|
---@return string
|
|
function Command:__tostring()
|
|
return "Command(" .. self.command .. ")"
|
|
end
|
|
|
|
---@param prefix string
|
|
function Command:New(prefix)
|
|
local self = setmetatable({}, Command)
|
|
|
|
self.prefix = prefix
|
|
self.commands = {}
|
|
|
|
_G['SLASH_' .. prefix:upper() .. '1'] = "/" .. prefix
|
|
SlashCmdList[prefix:upper()] = function(msg, editbox)
|
|
self:OnCommand(msg)
|
|
end
|
|
|
|
return self
|
|
end
|
|
|
|
---@param command string
|
|
---@param helpmsg string
|
|
---@param cb fun(args: table)
|
|
---@return nil
|
|
function Command:Register(command, helpmsg, cb)
|
|
self.commands[command] = {
|
|
helpmsg = helpmsg,
|
|
cb = cb
|
|
}
|
|
end
|
|
|
|
---@param msg string
|
|
---@return table
|
|
function Command:Parse(msg)
|
|
local args = {}
|
|
for arg in msg:gmatch("%S+") do
|
|
table.insert(args, arg)
|
|
end
|
|
|
|
return args
|
|
end
|
|
|
|
---@param msg string
|
|
---@return nil
|
|
function Command:OnCommand(msg)
|
|
local args = self:Parse(msg)
|
|
|
|
if #args == 0 then
|
|
self:PrintHelp()
|
|
return
|
|
end
|
|
|
|
local runner = self.commands[args[1]]
|
|
if runner then
|
|
runner.cb(args)
|
|
end
|
|
end
|
|
|
|
---@return nil
|
|
function Command:PrintHelp()
|
|
for k, v in pairs(self.commands) do
|
|
print('/' .. self.prefix .. ' ' .. k .. " - " .. v.helpmsg)
|
|
end
|
|
end
|
|
|
|
return Command
|
|
|