Better way to do this

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

Noob question but is there a better way to excute a block of code for once than this:

var do-once=true

func process():
if do-once:

:bust_in_silhouette: Reply From: cm

There are other ways for sure, though not necessarily better.

A boolean guard like you have is perfectly fine for most cases, though note that it is not thread-safe. But unless you’re working with threads you don’t have to worry about that.

thanks, the problem is in this way i have millions of variables at the start of script.

horsecar123 | 2022-05-15 13:19

Can you provide more context on how you’re using these guards? What type of functionality are you trying to achieve?

Rather than examining options for guarding a single method I get the feeling the question should be more about structuring your project to avoid the use of many single-shot blocks of code.

cm | 2022-05-15 13:38

:bust_in_silhouette: Reply From: Gluon

If your concern is that you have too many booleans then another option is a dictionary with key value pairs which do the same thing for instance;

var booleans_dict = {"key1": false, "key2: false, "key3": false}

change the key1 etc to words which mean something in your code and you can access them like this

func process():
    if booleans_dict["key1"] == false:
        do your stuff here
        booleans_dict["key1"] = true

or you could use 0 and 1 rather than true and false if you wanted.

:bust_in_silhouette: Reply From: SnapCracklins

Not to mention something obvious, but if you only want something to run once, don’t run it in process. Process runs every frame. Instead, put what you want to do in a function and run that when you need it to.

:bust_in_silhouette: Reply From: Inces

Turn attention to signals and setget. These are two good general ways to design code running limited and controlled amount of times