Using Prototypes

Previous topic - Next topic

XanthorXIII

Hello,
Long time no see ;) I'm thinking about adding Prototypes to my game. The reasoning for this is wanting Callbacks. Am I correct that I can use Prototypes in this manner?
Thanks.
Owlcat has wise

Kitty Hello

Yes. A prototype defines the parameters for a callback. And you can use a callback-type obejct to call a function trhough a pointer to that function. It's pretty easy once you understand how it works. A prototype-variable is just a pointer.

Slydog

If it helps, here a very modified excerpt from my GUI system that uses PROTOTYPES for 'click' function handlers.
This is NON PLAYABLE, just for reference, and wont compile!

Code (glbasic) Select
// My BUTTON TYPE
PROTOTYPE PGui_Button_Click: id%

TYPE TGui_Button
id%
fn_click AS PGui_Button_Click
// . . . other member variables . . . .

// Initialize button . . .
FUNCTION Set%: caption$, x%, y%, fn_click AS PGui_Button_Click
    ...
self.id = 1000
self.fn_click = fn_click
...
ENDFUNCTION

FUNCTION IsClick:
// Code to determine if this button has been pressed, then released . . .
IF (Input_IsClick(xy, 0, TRUE) = TRUE) AND (_mouse[0].b1_prev = FALSE)
self.details.state = GUI_STATE_ACTIVE
ELSEIF self.details.state = GUI_STATE_ACTIVE
// Cancel 'Click' if touch is outside button and 'Touch' still active
IF (Input_IsClick(xy) = FALSE) AND (_mouse[0].b1 = TRUE)
self.details.state = GUI_STATE_NORMAL
ENDIF
// 'Touch' finished (CLICK!)
IF _mouse[0].b1 <> TRUE
self.details.state = GUI_STATE_NORMAL
IF self.details.id_sound <> BLANK THEN _Sound.Effect_Play(self.details.id_sound)
// Button has been clicked, so call requested function, if it has been set.
IF self.fn_click = TRUE
self.fn_click(self.id)
ENDIF
ENDIF
ENDIF
ENDFUNCTION
ENDTYPE


In another file, here's how you use it:
Code (glbasic) Select
// How to add a button and specify a function to call when clicked
GLOBAL gui_button_play AS TGuiButton

// main game loop . . . .
Menu_Main_Initialize()

WHILE game_state <> STATE_QUIT
SELECT game_state
CASE STATE_MENU_MAIN
// Check if Main Menu's 'PLAY' button has been clicked, if so it's specified click handler will trigger.
gui_button_play.IsClick()
CASE STATE_MENU_WORLD_SELECT
// . . .
ENDSELECT

SHOWSCREEN
WEND

FUNCTION Menu_Main_Initialize:
LOCAL fn_button_play AS PGui_Button_Click
fn_button_play = Menu_Main_Play
gui_button_play.Set("PLAY", 10,  50, fn_button_play)
ENDFUNCTION

FUNCTION Menu_Main_Play: id%
DEBUG "Play Button Pressed!"
GameState(STATE_MENU_WORLD_SELECT)  // Now display 'World Select' menu
ENDFUNCTION
My current project (WIP) :: TwistedMaze <<  [Updated: 2015-11-25]