brl_hook.md 3.9 KB


id: brl.hook title: BRL.Hook

sidebar_label: BRL.Hook

This module provides a generic way to hook into various BlitzMax commands, and to add support for hooks into your own code.

The following hook ids are currently used by BlitzMax modules:

Hook id Description Data
FlipHook A Max2D Flip is about to occur Null
EmitEventHook An event has been emitted by a call to EmitEvent A TEvent object

To hook into any of these functions, use AddHook with the specified hook id and your hook function.

To provide hook support for your own code, use AllocHookId to generate a valid integer hook id somewhere in your program's startup code. Then, when the section of code you would like to be 'hookable' is about to execute, simply call RunHooks with the previously generated hook id and your own custom 'data' object.

Functions

Function AllocHookId()

Allocate a hook id

The returned hook id can be used with AddHook, RunHooks and RemoveHook.

Returns

An integer hook id

Example

SuperStrict

Global myHookID:Int=AllocHookId()

' This function will be called everytime RunHook is executed due to the AddHook action below
Function MyHook:Object( id:Int,data:Object,context:Object )
	Global count:Int
	
	count:+1
	If count Mod 10=0 Then
		Print "Flips="+count
	End If
	
End Function

'Add the MyHook function to our hook ID
AddHook myHookID,MyHook

'Some simple graphics
Graphics 640,480,0

While Not KeyHit( KEY_ESCAPE )

   Cls
   DrawText MouseX()+","+MouseY(),0,0
   RunHooks myHookID, Null
   Flip

Wend


Function AddHook( id,func:Object( id,data:Object,context:Object ),context:Object=Null,priority=0 )

Add a hook function

Add a hook function to be executed when RunHooks is called with the specified hook id.

Returns

A hook object that can be used with the RemoveHook command.

Example

SuperStrict

'This function will be automagically called every Flip
Function MyHook:Object( id:Int,data:Object,context:Object )
	Global count:Int
	
	count:+1
	If count Mod 10=0 Then
		Print "Flips="+count
	End If
	
End Function

'Add our hook to the system
AddHook FlipHook,MyHook

'Some simple graphics
Graphics 640,480,0

While Not KeyHit( KEY_ESCAPE )

	Cls
	DrawText MouseX()+","+MouseY(),0,0
	Flip

Wend


Function RunHooks:Object( id,data:Object )

Run hook functions

RunHooks runs all hook functions that have been added for the specified hook id.

The first hook function is called with the provided data object. The object returned by this function is then passed as the data parameter to the next hook function and so on. Therefore, hook functions should generally return the data parameter when finished.

Returns

The data produced by the last hook function


Function RemoveHook( id,func:Object( id,data:Object,context:Object ),context:Object=Null )

Remove a hook function

Removes the hook function specified by id, func and context.