Search code examples
ocamlsdl

how do I check the pressed down key using TSDL in OCAML?


This is the piece of code I want to write in OCAML taken from a C++ tutorial :

// Set texture based on current keystate
 const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL );
 if ( currentKeyStates[ SDL_SCANCODE_UP ] ) {
    currentTexture = &gUpTexture;
} else if( currentKeyStates[ SDL_SCANCODE_DOWN ] ) {
    currentTexture = &gDownTexture;
} else if( currentKeyStates[ SDL_SCANCODE_LEFT ] ) {
    currentTexture = &gLeftTexture;
} else if( currentKeyStates[ SDL_SCANCODE_RIGHT ] ) {
    currentTexture = &gRightTexture;
} else {
    currentTexture = &gPressTexture;
}

This C code uses the SDL library. In OCAML, I use the TSDL library which is thin bindings to the SDL library.

Here's the signature for SDL_GetKeyBoardState

val get_keyboard_state : unit -> (int, Bigarray.int8_unsigned_elt) bigarray

I am not quite sure how to do

currentKeyStates[SDL_SCANCODE_UP]

in OCAML.

Please help? Thank you!

This is what I've tried so far :

let key_state = Sdl.get_keyboard_state () in
key_state.(Sdl.Scancode.up)

The error states that .() cannot be applied to bigarrays...


Solution

  • You need to use .{} for indexing Bigarrays:

    key_state.{Sdl.Scancode.up}