Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- event system
- -- class 'event'
- events = {
- eventList = {},
- callbacks = {}
- }
- events.__index = events
- -- register an event type
- events.register = function(event)
- table.insert(events.eventList, event)
- end
- -- subscribe to an event and provide an callback function to be called
- events.subscribe = function(event, callbackFunc)
- local eventId = events.getId(event)
- table.insert(events.callbacks[eventId], callbackFunc)
- end
- -- get eventId by name
- events.getId = function(event)
- for id, eventName in pairs(events.eventList) do
- if type(eventName) == 'string' and
- eventName == event then
- return id
- end
- end
- end
- -- fire an event, invokes all subscribed callback functions
- events.fire = function(event, param1, param2, param3, param4, param5)
- local eventId = events.getId(event)
- if type(events.callbacks[eventId]) == 'table' then
- for _,callbackFunc in pairs(event.callbacks[eventId]) do
- if param5 ~= nil then
- callbackFunc(param1, param2, param3, param4, param5)
- elseif param4 ~= nil then
- callbackFunc(param1, param2, param3, param4)
- elseif param3 ~= nil then
- callbackFunc(param1, param2, param3)
- elseif param2 ~= nil then
- callbackFunc(param1, param2)
- elseif param1 ~= nil then
- callbackFunc(param1)
- else
- callbackFunc()
- end
- end
- end
- end
- -- queue an event
- events.queue = function(event, param1, param2, param3, param4, param5)
- os.queueEvent(event, param1, param2, param3, param4, param5)
- end
- -- event queue
- events.main = function ()
- -- stop Condition for main event loop
- local stop = false
- -- main event loop
- while not stop do
- local event, param1, param2, param3, param4, param5
- = os.pullEvent()
- -- fire an catched event
- events.fire(event, param1, param2, param3, param4, param5)
- end
- end
- -----------------------------------------------------------------------
- network = {
- packetStack = {}
- }
- network.__index = index
- -- queue Packet
- network.queuePacket = function(senderId, message)
- table.insert(packetStack, {
- sender = senderId,
- message = message
- })
- end
- -- main loop
- network.main = function()
- -- stop Condition for main event loop
- local stop = false
- -- main event loop
- while not stop do
- local event, senderId, message, distance
- = os.pullEvent('redstone_message')
- network.queuePacket(senderId, message)
- end
- end
- -----------------------------------------------------------------------
- -- register all events we want to listen for
- events.register('rednet_message')
- events.register('timer')
- events.register('disk')
- events.register('disk_eject')
- events.register('peripheral')
- events.register('peripheral_detach')
- events.register('redstone')
- events.register('network_receive')
- parallell.waitForAll(events.main, network.main)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement