cbox/lua/cbox/cl_hooks.lua

66 lines
1.5 KiB
Lua

local hookTable = {}
if cbox.hooks then
hookTable = cbox.hooks.GetTable()
end
cbox.hooks = cbox.hooks or {}
---Returns all hooks
---@return table
function cbox.hooks.GetTable()
return hookTable
end
---@alias ValidHooks
---| '"PreChatAddText"' # Runs before the true chat.AddText is called, allows modification to arguments
---Adds a hook
---@param name ValidHooks
---@param identifier string
---@param callback function
function cbox.hooks.Add(name, identifier, callback)
hookTable[name] = hookTable[name] or {}
hookTable[name][identifier] = callback
end
---Removes a hook
---@param name ValidHooks
---@param identifier string
function cbox.hooks.Remove(name, identifier)
if not hookTable[name] then return end
hookTable[name][identifier] = nil
end
cbox.detours = cbox.detours or {}
cbox.detours.chat_AddText = cbox.detours.chat_AddText or chat.AddText
local origChatAddText = cbox.detours.chat_AddText
function chat.AddText(...)
local args = {...}
local hooks = hookTable.PreChatAddText or {}
for id, callback in next, hooks do
local function catch(err)
cbox.utils.RealmError(("Failed to run callback for PreChatAddText hook %q:"):format(id), err)
end
local ok, ret = xpcall(callback, catch, args)
if not ok then continue end
if ret ~= nil then
if not istable(ret) then
cbox.utils.RealmError(("Got return for PreChatAddText hook %q, but it was not a table."):format(id))
continue
end
args = ret
end
end
origChatAddText(unpack(args))
hook.Run("OnChatAddText", args)
end