boozook / playdate

Playdate Build Tools and API
https://mastodon.gamedev.place/@pd
MIT License
133 stars 8 forks source link

Add example for updating state in serial message callback #375

Closed paulyoung closed 2 months ago

paulyoung commented 3 months ago

I wanted to share this example since I think it's a fairly reasonable thing to want to do.

This currently fails with:

error: error[E0501]: cannot borrow `*self` as mutable because previous closure requires unique access
  --> api/system/examples/update-state-in-serial-message-callback.rs:32:5
   |
28 |                   System::Default().set_serial_message_callback(Some(|msg| {
   |                   -                                                  ----- closure construction occurs here
   |  _________________|
   | |
29 | |                                      self.latest_message = Some(msg);
   | |                                      ------------------- first borrow occurs due to use of `self.latest_message` in closure
30 | |                                  }));
   | |____________________________________- argument requires that `self.latest_message` is borrowed for `'static`
31 |
32 |                   self.set_update_handler();
   |                   ^^^^ second borrow occurs here

The workarounds that I came up with so far weren't very satisfying and basically bypassed State altogether.

paulyoung commented 3 months ago

I think I have a version of this that seems reasonable. I’ll push that and then perhaps we can discuss alternatives.

paulyoung commented 3 months ago

I suspect that trying to update other parts of the state within event (or otherwise access self) will still be problematic.

I’ll add that and see what comes up.