uranium-core/uranium/events.lua

52 lines
1.1 KiB
Lua
Raw Permalink Normal View History

2023-05-04 16:29:26 +02:00
useProfiler = false
---@class ProfilerInfo
---@field public t number
---@field public src string
---@type table<string, ProfilerInfo>
2023-05-04 16:29:26 +02:00
profilerInfo = {}
local callbacks = {}
2023-05-04 16:29:26 +02:00
local debugCache = {}
---@param event string
---@param ... any
---@return any
--- Call a defined callback.
function uranium.call(event, ...)
if callbacks[event] then
2023-05-04 16:29:26 +02:00
profilerInfo[event] = {}
for _, callback in ipairs(callbacks[event]) do
2023-05-04 16:29:26 +02:00
local start = os.clock()
local res = callback(unpack(arg))
local dur = os.clock() - start
if useProfiler then
2023-05-04 16:29:26 +02:00
if not debugCache[callback] then
debugCache[callback] = debug.getinfo(callback, 'Sl') -- cached cus debug.getinfo is EXPENSIVE
end
local finfo = debugCache[callback]
table.insert(profilerInfo[event], {
src = finfo.short_src .. ':' .. finfo.linedefined,
t = dur
})
end
if res ~= nil then return res end
end
end
end
---@param event string
---@param f function
--- Register a callback handler.
function uranium.on(event, f)
if not callbacks[event] then
callbacks[event] = {}
2023-05-04 16:29:26 +02:00
end
table.insert(callbacks[event], f)
2023-06-02 11:03:42 +02:00
end