Advertisement
NanoBob

Event system v2

Aug 9th, 2015
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.75 KB | None | 0 0
  1.  local events={}
  2.  
  3. function add(name)
  4.    if events[name]==nil then
  5.       events[name]={
  6.       }
  7.    else
  8.       return false,"This event already exists."
  9.    end
  10. end
  11.  
  12. function addHandler(event,func)
  13.    if events[event]==nil then
  14.       events[event]={}
  15.       --   return true,"Event did not yet exist, event was added"
  16.    end
  17.    events[event][#events[event]+1]={
  18.       ["func"]=func,
  19.    }
  20. end
  21.  
  22. function removeHandler(event,func)
  23.    if events[event]==nil then
  24.       return false,"There is no such event"
  25.    end
  26.    for id,data in pairs(events[event]) do
  27.       if data.func==func then
  28.          events[event][id]=nil
  29.          return true,"Event handler succesfully removed"
  30.       end
  31.    end
  32.    return false,("No handlers for that function")
  33. end
  34.  
  35. function remove(event)
  36.     if events[event]==nil then
  37.         return false,"No such event exists."
  38.     end
  39.     events[evenf]=nil
  40.     return true,"Event (and it's handlers) succesfully removed"
  41. end
  42.  
  43. function trigger(event, ... )
  44.     if events[event]==nil then
  45.         return false,"No such event exists"
  46.     end
  47.     for id, data in pairs(events[event]) do
  48.         data.func(...)
  49.     end
  50. end
  51.  
  52. local computerCraft={
  53.     "char","key","key_up","paste","timer","alarm","task_complete","redstone","terminate","disk","disk_eject","peripheral","peripheral_detach","rednet_message","modem_message","http_success","http_failure","mouse_click","mouse_up","mouse_scroll","mouse_drag","monitor_touch","monitor_resize","term_resize","turtle_inventory"
  54. }
  55.  
  56. function setupComputercraftEvents()
  57.     for _,event in ipairs(computerCraft) do
  58.         add(event)
  59.     end
  60. end
  61. setupComputercraftEvents()
  62.  
  63. function handleCCEvents(timeOut)
  64.     if timeOut~=nil then
  65.         os.startTimer(timeOut)
  66.     end
  67.     local event,a1,a2,a3,a4,a5=os.pullEvent()
  68.     trigger(event,a1,a2,a3,a4,a5)
  69. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement