smack0007 / SDL_ts

SDL bindings for TypeScript. Currently running on deno.
MIT License
26 stars 6 forks source link

Add SDL_WaitEvent and SDL_WaitEventTimeout #14

Closed jingkaimori closed 1 year ago

jingkaimori commented 1 year ago

These two api will wait a long time until next event arrives. #7

An async iterator using SDL_WaitEvent shown here:

const SDLEvents: AsyncIterator<SDL.Event, never, SDL.Event | undefined> = (() => {
  let _event = new SDL.Event();
  return {
    next(event): Promise<IteratorResult<SDL.Event, never>> {
      if (event) {
        _event = event;
      }
      return new Promise<IteratorResult<SDL.Event, never>>((resolve, reject) => {
        const res = SDL.WaitEvent(_event);
        if (res == 0) {
          reject(SDL.GetError());
        } else {
          resolve({
            done: false,
            value: _event,
          });
        }
      });
    },
  };
})();
smack0007 commented 1 year ago

Thinking: There is a Memory class that contains right now only a single method to read memory. Maybe your AsyncIterator example can be packed into an Events class. Maybe something like:

for await (const _event of Events.asyncIterator()) {
// ...
}
smack0007 commented 1 year ago

I couldn't quite get this to work. SDL_WaitEvent works on it's own but Events.asyncIterator doesn't seem to. Did you test Events.asyncIterator() locally? Can you please provide a simple example project?

You can see my testing here: https://github.com/smack0007/SDL_ts/tree/wait-event I tried to modify the hello-world example to use the Events.asyncIterator() method. I'm not exactly a whiz at async iterators but I would like to know that the Events.asyncIterator() method actually works before merging.

Nevermind I got it to work.

smack0007 commented 1 year ago

Please copy the hello-world-async example from here: https://github.com/smack0007/SDL_ts/tree/wait-event/examples/hello-world-async

You'll also need to export Events from mod.ts:

export * from "./src/events.ts";
smack0007 commented 1 year ago

Ok looks good to me now. Thank you for your time and contribution.