Chaining method calls like objects in javascript

Godot Version

4.5

Question

Hi there,

i come from a webdeveloper background and whatever anybody want to say about js is ok. But i like the possibility to chain things like this:

game.state.saves.load(savegame_name)

is it possible to do this in gdscript? I thought about an autoload file (in this case “game.gd” ) with a “method-tree” like that. I tried it with a dictionary and classes but don’t get it to work properly. I think this could clean up a lot in my code.

thanks for any advice.

Dot syntax works the same as in most other languages that support it, javascript icluded. And yeah, you should be able to access dictionary entries with it.

Post some code that is not working as expected.

2 Likes
var save_test :={
	'save': test
}


func test(hello):
	print(hello)


func _ready():
	save_test.test()

results in: …test() not found….

You need to use Callable.call() with Callables which save_test.save is one. So it should be save_test.test.call()

1 Like

There’s a bunch of things wrong in your example.
You should be referencing the keys, not values.
In your case, save_test.save will work and will retrieve the callable test.
You can then call() this callable.
And you haven’t defined hello, so it would throw an error on that line too, I changed it to just a string “hello” in my example

So the full working syntax would be:

var save_test :={
	'save': test
}

func _ready() -> void:
	save_test.save.call()

func test():
	print("hello")
1 Like

sorry. that was a “to fast written” error. i mean save_test.save() and not save_test.test(). But i see, so i have to call it everytime with this .call()

Thanks to everybody for the quick help.

Yes. Imho that’s the only annoying thing with function references in GDScript. I really don’t understand why it isn’t allowed to just call the callable by appending parentheses to its name, like in most other languages.

1 Like

Yeah, also it did not show in the editor the possible params to give to the method. That is annoying me the most.

That’s because when you retrieve it from a Dictionary, it’s not interpreted by the Editor yet, so it doesn’t know the type of the retrieved value, so it doesn’t know what autocomplete options to give you.
It would give you the autocomplete options directly on the callable though, like it’s seen here:

1 Like

You already got an answer, but you also get auto-complete options if you declare the type of your dictionary like this:


var save_test : Dictionary[String, Callable] = {
	'save': test
}
2 Likes

Thank you, this make things so much easier.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.