Is it possible to use "anonymous functions" in GDScript?

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

For some background, I had a button-based text game built through Flash/AS3. Since that died, I’m looking for an alternative to build with, and Godot is looking very promising.

One thing that I utilized with great success in AS3 were “anonymous functions” - a function you could re-build to do various things in runtime.

The benefit was with the buttons. Rather than swapping out button objects over and over to achieve different outcomes when pressed (or rather than passing some game-state information to reference a massive table to determine outcome), I was able to simply re-define the function that was performed when the button was clicked, based on context.

For example, if the player was currently in event A, Button-1 would trigger the function “B1-Pressed”, which was previously defined to perform action B. But, if the player was currently in event X, “B1-Pressed” would instead be re-defined to perform action Y. This made things much easier because there were hundreds to thousands of different outcomes for Button-1, depending on what the current context of the world is, allowing for much easier readability and organization of code, as well as workflow.

However, I didn’t see how such a thing was possible in GDScript. I did find this doc and I think it means my desire may not be possible, but I could be misinterpreting it:

Is an equivalent to the “anonymous function” possible with GDScript? Or will I have to rely on the C# integration?

btw as3 lives through starling

Reloecc | 2020-09-14 10:56

:bust_in_silhouette: Reply From: klaas

Hi,
Godot knows no lambda functions.
But you can use object.call to do what you suppose to do…

Instead of refrering to a function pointer you can use a string with the function name to do so.

var funcToCall = "funcName"

Func on_button_pressed():
    call(funcToCall)

func funcName():
    #next time do something other
    funcToCall = "anotherFunc"

func anotherFunc():
    #and back again
    funcToCall ="funcName"

Thanks! That might be a workaround I go with then! It will still require a lot more named functions to be created, so I’ll have to debate with myself if I go that route or C#.

Xad | 2020-09-14 20:51

This is really old but it’s the first one I found so I though I’d just add to this - I don’t know if it wasn’t available in previous gdscript versions, but in Godot 4 you can write anonymous functions.

Here’s an example:

func available_paths() -> Array:
	return $EnemyPaths.get_children() \
		.filter(func(path : Path2D): return path.visible)