Skip to content

Instantly share code, notes, and snippets.

@katsaii
Created August 19, 2020 13:04
Show Gist options
  • Save katsaii/9921e166fc8121b3b9e42b6fabde5a77 to your computer and use it in GitHub Desktop.
Save katsaii/9921e166fc8121b3b9e42b6fabde5a77 to your computer and use it in GitHub Desktop.
Defer execution of a block until another block is complete.
/* Deferred Exeuction of Code
* --------------------------
* Kat @Katsaii
*/
#macro DEFER for (;; {
#macro UNTIL ; break; })
@katsaii
Copy link
Author

katsaii commented Aug 19, 2020

This works similar to defer in languages such as Go or Zig. Execution of the block between the macros DEFER and UNTIL is deferred until the execution of the block after UNTIL.

Destroying a list after three elements are added

var list = ds_list_create();
DEFER {
  ds_list_destroy(list);
} UNTIL {
  ds_list_add(list, 1);
  ds_list_add(list, 2);
  ds_list_add(list, 3);
}

Closing a text file after its content is read

var file = file_open_text("test.txt");
var msg = "";
DEFER file_close(file) UNTIL {
  while (!file_text_eof(file)) {
    msg += file_text_readln(file);
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment