Wiki

Clone wiki

asss / Callback

Callbacks

Callbacks are simple functions that are called when certain events occur. They are tools to allow modules to be notified of events that have happened on the server. Many callbacks are related to actions a player has taken, or an event in a game. Callbacks provide one-way communication from the calling module. For bidirectional communication, Interfaces or Advisers should be used.

Properties of callbacks

  • Function returning void.
  • Any number of callbacks can be registered for an event type on a scope. Registering a callback on an arena scope will also get notifications coming from the global scope.
  • All registered callbacks will be used when a callback type is invoked (unlike interfaces).

Conventions

  • type definition: typedef void (*CallbacktypeFunc)(<params>);
  • callback identifier: CB_CALLBACKTYPE
  • callback identifier version: "callbacktype" or "callbacktype-version"

Callbacks are registered using Imodman's RegCallback(<callback identifier>, <callback function>, <scope>) where <scope> is an arena or the identifier ALLARENAS. Use UnregCallback with the same paramaters to unregister the callback.

Examples

Registering a callback

/* interface pointer */
local Ichat *chat;

/* prototype for our callback function */
local void playeraction(Player *, int action, Arena *);

/* entry point for the 'greeter' module */
EXPORT int MM_greeter(int action, Imodman *mm, Arena *a)
{
	if (action == MM_LOAD)
	{
		/* get the chat interface for later. */
		chat = mm->GetInterface(I_CHAT, ALLARENAS);
		if (!chat)
			return MM_FAIL;
			
		/* register our callback */
		mm->RegCallback(CB_PLAYERACTION, playeraction, ALLARENAS);
		
		/* return success */
		return MM_OK;
	}
	else if (action == MM_UNLOAD)
	{
		mm->UnregCallback(CB_PLAYERACTION, playeraction, ALLARENAS);
		mm->ReleaseInterface(chat);
		return MM_OK;
	}
	return MM_FAIL;
}

Sample callback function

/* CB_PLAYERACTION callback function. */
local void playeraction(Player *p, int action, Arena *a)
{
	if (action == PA_ENTERARENA)
	{
		/* use the Ichat interface to send green text to the player when they enter the arena. */
		chat->SendMessage(p, "Welcome to the %s arena, %s!", a->name, p->name);
	}
}

Callback type definition

/* callback identifier and version */
#define CB_PLAYERACTION "playeraction"
/* callback function type */
typedef void (*PlayerActionFunc)(Player *p, int action, Arena *arena);

Executing callbacks

/* executes all registered playeraction callbacks for the current arena, and passes PA_ENTERARENA as the action for the Player p. */
DO_CBS(CB_PLAYERACTION, arena, PlayerActionFunc, (p, PA_ENTERARENA, arena));

Updated