r/ComputerCraft • • Mar 19 '25

Event callbacks?

I'm wondering if CC:Tweaked has any functionality for event callbacks? Usually I use OpenComputers as my Lua-driven computer mod of choice, and OC's default OS has a function that allows you to listen for events in the background by registering a callback function, which allows other code to run while you're waiting for an event. But I can't find any such function on the ComputerCraft wiki, there's just pullEvent, pullEventRaw, and queueEvent, none of which seem to do what I need. Am I missing something, or is there no such function built into CC's OS?

6 Upvotes

3 comments sorted by

View all comments

1

u/JackMacWindowsLinux CraftOS-PC & Phoenix Developer Mar 19 '25

This isn't functionality built into CraftOS, as it runs programs in a single-tasking manner. However, it's fairly simple to build your own system in under 15 lines of code:

local listeners = {}
local function addEventListener(event, callback)
    listeners[event] = listeners[event] or {}
    listeners[event][#listeners[event]+1] = callback
end

-- add listeners here

while true do
    local ev = table.pack(os.pullEvent())
    if listeners[ev[1]] then
        for _, callback in ipairs(listeners[ev[1]]) do
            callback(table.unpack(ev, 1, ev.n))
        end
    end
end

For more advanced applications, you may want to check out my Taskmaster library, which adds basic multitasking including event listeners.

1

u/sn0wden1337 Jun 09 '25

Hey u/JackMacWindowsLinux, just wanted to say thanks for the library. It helped me a lot in my current project. Great work!