I have an array of functions but they execute themself without any trigger

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

I have an array and a variable which is:

var steps = [ step1(), step2(), step3() ]
var currentStep = 0

and have some functions that goes like:

func _input(event):

if event.is_action_pressed(“ui_accept”):

executeStep()

func executeStep():

steps[currentStep]
currentStep += 1

func nextStep():

currentStep += 1

My problem is when I start the game it triggers all 3 steps even before I click anything(for now steps only prints numbers in command). I thinks it’s because of the way I wrote the array cause tried to CTRL + K everything else but it still was the same. Is there a way to do this other that 100 if else statements?

:bust_in_silhouette: Reply From: haydenv

Option 1: Use match

Instead of too much if elif else we can try using match.

func executeStep():
    match currentStep:
        0:
            step1()
        1:
            step2()
        2:
            step3()
    currentStep += 1

If you go with this option then you won’t need the steps array anymore.

Option 2: Use Callables

We can use a Callable to store a function, and then we can call the function any time we want (as many times as we want).

var steps = [Callable(self, "step1"), Callable(self, "step2"), Callable(self, "step3")]
var currentStep = 0

func executeStep():
    steps[currentStep].call()
    currentStep += 1

If we need to pass in arguments we go steps[currentStep].call(arg1, arg2, arg3), where for example I passed in three arguments.

As an addendum I will show a way to avoid typing Callable 100 times, if there are 100 steps.

const numberOfSteps = 100
var steps = []
var currentStep = 0

func _ready():
    for i in range(numberOfSteps):
        var functionName = "step" + str(i + 1)
        var callable = Callable(self, functionName)
        steps.append(callable)

haydenv | 2022-07-12 11:07

Thank you god sir for sparing some time and helping me

MemokingMH | 2022-07-12 15:54