Function inside function

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

I have an array:

array = ["option1", "option2", "option3"]
var selected_option

I have function assigned on an Input event:

func _input(event): 
if event is InputEventKey:
if event.is_action_pressed("select_option"):
selected_option = array[randi() % array.size()]

And then I want to execute different functions based on the selected option:

func execute_option():
if selected_option =="option1": play_option1()
if selected_option == "option2": play_option2()
if selected_option == "option3": play_option3()

func play_option1(): print("Option 1 is selected")
func play_option2(): print("Option 2 is selected")
func play_option3(): print("Option 3 is selected")

So what I want to ask is that is there another less complicated way to do this. The reason I don’t just print at the first function is that I want to do more with each option than just printing.

:bust_in_silhouette: Reply From: Wakatta

Firstly a less complicated way is to use one function passing in different params

func execute_option(option):
    match option:
        "option1": 
            print("Option 1 is selected")
            # do other option 1 stuff
        "option2": 
            print("Option 2 is selected")
            # do other option 2 stuff
        "option3": 
            print("Option 3 is selected")
            # do other option 3 stuff

Answering your question as is, you can use the call method however your functions must have the same name as the options

var array = ["option1", "option2", "option3"]

func _input(event): 
    if event is InputEventKey:
        if event.is_action_pressed("select_option"):
            var option = array[randi() % array.size()]
            call(option)

func option1(): print("Option 1 is selected")
func option2(): print("Option 2 is selected")
func option3(): print("Option 3 is selected")

Ok thank you, the call method works wonderfully.

chaosreborn1 | 2021-12-02 00:36

:bust_in_silhouette: Reply From: timothybrentwood

If you can make it so your array contains the names of your functions as a string you can just do:

array.shuffle()
call(array.front())

Otherwise the only way you can clean it up a little is by using a match statement instead of the ifs.