Does GDScript has scope guard functionality?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Karol23

Hi,

does GDScript something like Scope Guard (object which has function which is called automatically at the end of scope)? (What is ScopeGuard in C++? - Stack Overflow)

Or at least does GDScript has tools to implement it by myself?

Thank you for the answers.

I’m pretty sure it doesn’t, but could you give an example on why this could be used for in GDScript? I thought the virtual methods such as tree_exited and such would do the job.

Joel Gomes da Silva | 2023-04-04 14:41

Hi, I think it’s useful in any language with scopes. Some general example would be a method which do some complex update of object inner state and at its end I would like to update related UI (call UI update method). Problem is that the update function is complex with a lot of early return and without the guard I would have to call UI update method at each place with return. But with guard, I would just create guard at the beginning and would not care anymore.

Karol23 | 2023-04-04 16:01

:bust_in_silhouette: Reply From: pox

Well there is _exit_tree() for that. What you want is to separe the update logic. I would just put all the update UI logic in another node or clean up the early returns in their own functions. If you really need a function that is always called at the end you could just hack it like so:

func _process(delta):
    update(delta)
    post_update(delta)

func update(delta):
    do logic stuff

func post_update(delta)
    do ui or animation stuff