function calling using Dictionaries

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By vonflyhighace2
:warning: Old Version Published before Godot 3 was released.

Can someone give me an example of how you would call a function from a dictionary in Godot I’ve asked this question before but I just can’t get it to work. An example would be ideal. Thanks

:bust_in_silhouette: Reply From: eska

You can save a function as a variable using funcref. This line will save the function node_func of the retrieved Node2D in the variable my_funcref:

var my_funcref = funcref( get_node("/root/my_scene/Node2D"), "node_func")

Just add this FuncRef to a dictionary:

var function_dictionary = {
	node_func = my_funcref
}

Then retrieve the function from the dictionary using the key you used and call it using call_func():

function_dictionary["node_func"].call_func() # or, for string keys, just:
function_dictionary.node_func.call_func()

Optionally hand any argument to the function as argumens to call_func()

Here’s a full example:

extends Node

func test_func():
	print("Success")

func _init():
	var my_funcref = funcref( self, "test_func")
	var function_dictionary = {
		my_key = my_funcref
	}
	function_dictionary.my_key.call_func()

(edited to fix formatting)

Thanks a lot. This was driving me batty trying to figure this out in GDScript. man, life saver.

vonflyhighace2 | 2016-04-03 01:21

On the last line of the “full example”, what is call_func? Where did that come from?

ogrotten | 2017-07-25 18:00

funcref(self, "test_func") creates a FuncRef object.
The FuncRef class has the method call_func, which simply calls the referenced function with the given arguments and returns its return value.

eska | 2017-07-25 20:05