godot: GDScript `range(0, 1, 0.1)` returns an empty array

Godot version

v3.4.3.rc1.official [894b6d504]

System information

Mac OSX (Intel 2019)

Issue description

Well actually it throws an error if you try and print that, but if you use it in a loop it just silently fails:

print(range(0.0, 1.0, 0.5))
Screenshot 2022-02-17 at 01 32 24
for i in range(0.0, 2.0, 0.1):
		print("HERE", i)

And Here never get’s printed.

Steps to reproduce

Please see above code samples

Minimal reproduction project

No response

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 15 (14 by maintainers)

Most upvoted comments

We can add a specific warning for this case, or maybe even an error since I don’t think there’s a valid case for using floats in range()

@cdemirer

for i in Vector3(0.0, 5.0, 1.5):
	print(i)

Wow I didn’t know about this. ~Seems aliasing range to vector3 can be a solution if it covers all cases 😅~

Edit: It’s not a good solution as we still need to do something like:

var my_range = range(0, 10)

Having this feature built into the language but only to those who know about it also doesn’t seem so kind to the developer. If I start to use Vector3 in my loops then others who come along later probably won’t understand at once.

Since

for i in Vector3(0.0, 5.0, 1.5):
	print(i)
0
1.5
3
4.5

works, wouldn’t it make sense to have a range equivalent?

Precision errors accumulate on floats, so it’s much better to keep integers for your iterator. Just divide it by whatever you need to have the float range you want, e.g.:

for i in range(20):
	print("HERE", i / 20.0)

That being said, using a float step in range() should probably raise a warning instead of just coercing the values silently.

I suppose an “frange” function could be useful, although of course the third parameter would be mandatory to know the increment.