Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » al_get_keyboard_state error

This thread is locked; no one can reply to it. rss feed Print
al_get_keyboard_state error
SaSSolino
Member #16,806
February 2018

Hi, I'm making this little tris game and I wanted to abilitate keyboard play, but I've ran into an issue: basically an exception occurs on al_get_keyboard_state(keySTate).

My code is somenthing like this:

...
ALLEGRO_EVENT_QUEUE *event_q = NULL;
...
al_install_keyboard();
...
event_q = al_create_event_queue();
...
al_register_event_source(event_q, al_get_keyboard_event_source());
... (start loop)
ALLEGRO_EVENT *event = NULL;
ALLEGRO_KEYBOARD_STATE *keyState = NULL;

al_wait_for_event(event_q, event);
al_get_keyboard_state(keyState);

if (al_key_down(keyState, ALLEGRO_KEY_Q))
//do things
... (end loop)

What did I mess up? ???

SiegeLord
Member #7,827
October 2006
avatar

That function takes a pointer that needs to point to some allocated memory. Right now your pointer points to nothing (note how you set it to NULL). The easiest way to resolve this is to allocate the state on the stack, like so:

There is one more issue just like that in your code, see if you can spot it.

"For in much wisdom is much grief: and he that increases knowledge increases sorrow."-Ecclesiastes 1:18
[SiegeLord's Abode][Codes]:[DAllegro5]:[RustAllegro]

SaSSolino
Member #16,806
February 2018

Thanks for the reply.

Edgar Reynaldo
Major Reynaldo
May 2007
avatar

You may not want to rely on the keyboard state, but rather keyboard events. It's fairly easy to track which keys are down.

int keys[ALLEGRO_KEY_MAX] = {0};

//... Wait for an event first

if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {keys[ev.keyboard.keycode = true;}
if (ev.type == ALLEGRO_EVENT_KEY_UP) {keys[ev.keyboard.keycode = false;}

//... Monitor key array inside logic code

if (keys[ALLEGRO_KEY_ESCAPE]) {Quit();}

Michael Weiss
Member #223
April 2000

That is almost exactly what I do also. (except my array is called 'key' instead of keys)

I thought when I implemented that in Allegro 5, I was doing something shady, like trying to revive the way things used to be in Allegro 4.

But seeing someone else do it as well, kind of legitimizes it, in my mind....

I have a question for Edgar.

In my program, I make my int key[] array global.

(I declare it outside of any function, and extern it in my main header file)

What would be a more elegant approach to this?
Not from a functional point, because it works just fine, just from a 'better programming style' point.

Edgar Reynaldo
Major Reynaldo
May 2007
avatar

A quick and dirty solution to global proliferation is functions.

Turn you key array into a bool Key(int k) {return keys[k];} function. Then you can hide the keys array in a module, and expose it through your function. This reduces global proliferation.

Go to: