The Events module provides functions for accessing and firing Events.
Here is an overview of the Events functions:
Function | Parameters | Results |
---|---|---|
collect | eventName… | EventQueue |
fire | eventName, data | nil |
intercept | eventNames, eventHandler | EventInterceptor |
on | eventName… | table |
Below you find short descriptions about each of the functions and some examples about how to use them in your spells.
The ‘collect’ function creates an EventQueue that collects all Event occurrences of the specified kind(s).
Echoing all chat messages.
local queue = Events.collect("ChatEvent")
while true do
local event = queue:next()
spell:execute("say %s", event.message)
end
Posting the position of all block-click events into the chat.
local queue=Events.collect("LeftClickBlockEvent","RightClickBlockEvent")
while true do
local event = queue:next()
spell:execute("say %s at %s", event.name, event.pos)
end
The ‘fire’ function posts a new CustomEvent with the given name and the optional given content data.
Firing a custom event without any data.
Events.fire("my-event")
Registering an event intereptor for a custom event that prints the event data.
Events.on("my-event"):call(function(event)
print(str(event.data))
end)
Firing a custom event with some data.
local data = spell.block
Events.fire("my-event", data)
Creates an event interceptor for Events with the specified names.
The interceptor will be called immediately when an event occurs, which allows events to be modified and canceled.
Event interceptors do not support sleeping - therefor, autosleep is disabled and manual sleeping is treated as an illegal operation.
As long as a Spell has any active event interceptors it will not terminate by itself, so make sure to stop each event interceptor that is no longer needed.
Intercepting chat events.
local interceptor =
Events.intercept({'ChatEvent'}, function(event)
print(str(event))
end )
Be careful, when accessing variables that are used both by the main program as well as by the event interceptor.
If autosleep is enabled, the main program can fall asleep eventually at any time, which allows that a variable might be modified in an awkward situation.
For instance, the following program fails due to indexing a nil value in line 10 despite the nil check in line 8.
In this example there is an explicit sleep in line 9, but that sleep could just as well be caused by autosleep.
local abc = 'abc'
local interceptor = Events.intercept({'my-event'}, function(event)
abc = nil
end)
spell:execute([[lua
Events.fire('my-event')
]])
if abc ~= nil then
sleep(1)
print(abc:len())
end
interceptor:stop()
Returns a table containing the specified event names and a reference to intercept. This can be used as shorthand for intercept.
Subscribing for chat events and printing the messages.
local interceptor = Events.on('ChatEvent'):call( function(event)
print(event.message)
end)