[TUTORIAL] Binding to events.

Started by ., Aug 23, 2016, 11:43 PM

Previous topic - Next topic

.

This is outdated. After reading this (it is still relevant!) go ahead and read this.

There are two types of events supported by the plugin. Global and local. Global events are emitted by the plugin core. Local plugins are emitted by instances of entities that you create. All events can be used as global but not all can be used as local. For example, you can't listen if an entity instance was created using the local event since it doesn't even exist for you to bind to that instance. But you can listen if it was destroyed using the local event since the instance exists already for you to bind to it.

A local event, once bound to a certain entity will only be triggered if only that entity emits that event. A global event, once bound to the plugin core will be emitted by anyone who triggers that event.

Binding to local events can be done through the SqCore.Bind function. Binding to local events can be done through the member function `Bind()` provided by each entity instance. They both have the same signature. Only the behavior is different.

If you're not a OOP enthusiast then local bindings will most likely be of no use to you. So using the global bindings is the best route to receive events from the plugin.

You can find a list of all events supported by the plug-in here. Some of them may not be documented yet. The one that are introduced by the plugin and have a different syntax and behavior than the official plugin have a higher priority to be documented.

Events can execute any callable function. Free functions, Anonymous functions, Lambdas or even Member functions which are the same thing as Free functions except with a class instance as the environment.

An event can only be assigned a single function to be called. If another function is bound, the previous one is no longer called. To stop listening for callbacks from events, you can bind a null value.



Binding a Free function to the server frame event:
local g_FrameCount = 0;

function onServerFrame(delta)
{
    printf("Server frame %d", ++g_FrameCount);
}

SqCore.Bind(SqEvent.ServerFrame, this, onServerFrame);



Binding an Anonymous function to the server frame event:
local g_FrameCount = 0;

SqCore.Bind(SqEvent.ServerFrame, this, function(delta)
{
    printf("Server frame %d", ++g_FrameCount);
});



Binding a Member function to the server frame event:
class Gamemode
{
    m_FrameCount = 0;

    function constructor()
    {
        SqCore.Bind(SqEvent.ServerFrame, this, onServerFrame);
    }

    function onServerFrame(delta)
    {
        printf("Server frame %d", ++m_FrameCount);
    }
}

GM <- Gamemode();

You can see that the event system is quite flexible and allows all sorts of designs to be achievable. Feel free to check the documentation for more.
.

DizzasTeR