--[[ Event Management System Centralized event dispatcher with priority-based routing ]] local events = {} -- Event queue and handler registry local eventHandlers = {} local handlerPriorities = {} --------------------------------------------- -- PRIORITY LEVELS (higher = more priority) --------------------------------------------- events.PRIORITY = { PASSWORD_INPUT = 100, -- Highest priority - password entry ENTITY_READ = 50, -- Entity tracking MESSAGE = 50, -- Message handling DISCONNECT_BUTTON = 30, -- Manual disconnect button ACTIVATION = 20, -- Incoming wormhole DISCONNECT_CHECK = 10, -- Natural disconnection TIMEOUT = 5, -- Timeout handlers DEFAULT = 1 -- Default priority } --------------------------------------------- -- HANDLER REGISTRATION --------------------------------------------- function events.registerHandler(eventType, callback, priority) priority = priority or events.PRIORITY.DEFAULT if not eventHandlers[eventType] then eventHandlers[eventType] = {} handlerPriorities[eventType] = {} end table.insert(eventHandlers[eventType], callback) table.insert(handlerPriorities[eventType], priority) end function events.clearHandlers(eventType) if eventType then eventHandlers[eventType] = {} handlerPriorities[eventType] = {} else eventHandlers = {} handlerPriorities = {} end end --------------------------------------------- -- EVENT DISPATCHER --------------------------------------------- function events.dispatch(eventType, ...) local handlers = eventHandlers[eventType] if not handlers or #handlers == 0 then return nil end -- Sort handlers by priority (highest first) local sortedHandlers = {} for i = 1, #handlers do table.insert(sortedHandlers, { callback = handlers[i], priority = handlerPriorities[eventType][i] }) end table.sort(sortedHandlers, function(a, b) return a.priority > b.priority end) -- Call handlers in priority order until one handles the event for _, handler in ipairs(sortedHandlers) do local result = handler.callback(...) if result ~= nil then return result end end return nil end --------------------------------------------- -- EVENT POLLING --------------------------------------------- function events.pullEvent(filter) while true do local eventData = { os.pullEvent(filter) } local eventType = eventData[1] local result = events.dispatch(eventType, table.unpack(eventData)) -- If a handler processed the event and returned something, return it if result ~= nil then return result, eventType, eventData end end end function events.waitForAny(...) local functions = { ... } return parallel.waitForAny(table.unpack(functions)) end return events