This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
kelevra.1337's profile picture

[Question] Event listener

Started by kelevra.1337, 01 January 2014 - 11:26 AM
kelevra.1337 #1
Posted 01 January 2014 - 12:26 PM
Hey everybody,

Ive seen the event.listen(name, callback) function in openComputers wiki and wondered if it would be possible to do something similar in CC.

Ive looked around in the forum but couldnt find anything like that and i have no idea how to do it myself.
Could someone briefly explain how to do it, or point me somewhere i can look it up?

Edit:

Nevermind, just found a solution, just forgot about the parallel API. The solution isnt pretty or even usefull since you cant really add event listeners or setup multiple listeners but it works for me, at least for now


local event
local callback
function callbackDummy()
while true do
  local revent =  {os.pullEvent(event)}
  callback()
end
end
function eventListener(mainfunc,eventname,callbackfunc)
event = eventname
callback = callbackfunc
parallel.waitForAny(mainfunc,callbackDummy)
end
Edited on 02 January 2014 - 07:19 PM
CometWolf #2
Posted 01 January 2014 - 01:20 PM
Don't think CC has anything exactly like that
https://github.com/MightyPirates/OpenComputers/wiki/API-Event
But using the os.pullEvent(similar to OC event.pull function), you could probably code it yourself.
http://computercraft.info/wiki/Os.pullEvent
kelevra.1337 #3
Posted 01 January 2014 - 05:55 PM
Sorry, couldnt answer the whole day.

Well, thats the thing, i cant figure out how to set up something sitting in the background waiting for an event. I tried messing with coroutines and got them kinda working but im far from being able to do something like an event listener i think.
kelevra.1337 #4
Posted 03 January 2014 - 03:00 PM
Ok, i dont know why i didnt came up with it earlier but here it is:


local listeners = {}
function addListener(event,func)
if listeners[event] == nil then
  listeners[event] = func
else
  error("a func for this event already exists")
end
end
function callbackDummy()
while true do
  local revent =  {os.pullEvent()}
  if listeners[revent[1]] ~= nil then
   listeners[revent[1]](revent)
  end
end
end
function eventListener(mainfunc)
parallel.waitForAny(mainfunc,callbackDummy)
end

only thing is, youll need to run you main code via eventListener() but other than that it works pretty well.
Maybe close this thread now?