This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

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():

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")
        return funcref(self, "ripple")

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

Function "funcref()" not found in base self

Godot version Godot 4 beta-9
in Engine by (15 points)
edited by

1 Answer

+1 vote
Best answer

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")
        return Callable(self, "ripple")

And when ready to use

var callable = get_callable(0), 4)

Repeat this is only for Godot 4 onwards

by (6,942 points)
selected by

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")

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!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.