Can I return a 'func' type from a function?

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

Can I return a ‘func’ type from a function?

Specifically, I would like to return a function (NOT IT’S VALUE!) from another function. Is this possible? Similar to how C# delegates would work.

For reference, I am using this unity tutorial, but converting it to gdscript, and am getting stuck on the section on setting up delegate functions.

I found FuncRef, but it doesn’t seem to be working properly with my library class.

class_name FunctionLibrary

func _init():
    pass
	
func wave(x : float, t : float) -> float:
    return sin(PI * x + t)

static func multiwave(x : float, t : float) -> float:
    var y : float = sin(PI * (x + 0.5 * t));
    y += 0.5 * sin(2.0 * PI * (x + t));
    return y * (2.0 / 3.0)

static func ripple(x : float, t : float) -> float:
    var d : float = abs(x)
    var y : float = sin(PI * (4.0 * d - t));
    return y / (1.0 + 10.0 * d)

func get_function(index : int):
    if (index == 0):
        return funcref(self, "wave")
    elif (index == 1):
        return funcref(self, "multiwave")
    else:
        return funcref(self, "ripple")

And I get the following error on the return lines of ‘get_function’:

Function “funcref()” not found in base self

:bust_in_silhouette: Reply From: Wakatta

Since you’re using Godot 4 what you need is a Callable

func get_callable(index : int):
    if (index == 0):
        return Callable(self, "wave")
    elif (index == 1):
        return Callable(self, "multiwave")
    else:
        return Callable(self, "ripple")

And when ready to use

var callable = get_callable(0)
callable.call(2, 4)

Repeat this is only for Godot 4 onwards

Was not going to say anything but cannot resist the urge to say that your code can also be written like this

func get_function(index : int):
    if index < get_method_list().size():
        return Callable(self, get_method_list()[index])
    return Callable(self, "_ready")

Wakatta | 2022-12-26 01:43

Ah, this worked perfectly - I had both the latest and 3.x docs up and was looking in the wrong one! It also looks like your refactoring will come in handly later in the tutorial, as that is exactly what I will need to use.

Thanks for your help!

SleepySheepy | 2022-12-26 02:50