+1 vote

So, GDScript allows static typing, which means defining the type of a variable, a very useful feature for, among other things, completion and reference.

Problem is, it seems it cannot be used to define the type of elements in an array (arrays, like in Python, can contain any type of data) and because of that I can't enjoy the advantages of static typing when iterating through an array.

Is there anyway to do something like this

for i in range(len(someArray)):
    var iterator:someType = someArray[i]

But instead as something like

for iterator:someType in someArray:
in Engine by (72 points)

You can't force the assignment of types in a 'for' loop, as each element the 'for' keyword loops over already has a different type.

Well... they can, but shouldn't I be able to declare to the code that I expect them not to?

Not really, as far as I've been able to determine. Like many dynamic languages, GDScript does not differentiate between the collection of arbitrary types (GDScripts Array), collections of fixed types (like NumPy's ndarray), and collections of a class or below. I had to code around to get array's of resources to auto populate with the right types and it still seems buggy.

1 Answer

0 votes

This is a place where the static typing makes things harder to read. You probably want:

for thing in SomeArray:
assert (Util.what(thing) == "expected Class")

where Util is the usual static library people write, using typeof and get_type

by (327 points)

I don't really want to assert it as much as I want the code to know what type my iterator is so I can use completion and other type checking features.

Like, I could do

for thing in someArray:
    var _thing:someType = thing

But should that mandatory extra step exist?

Yes, it should. You are looking for Python's __iter__/__next__ interface. GDScript gets enough extra complexity from gaming concepts (Scenes, Resources, signals, etc.) and chose not to allow the bells and whistles.

Perhaps we should bitch about language design over Zoom?

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 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 webmaster@godotengine.org with your username.