Operating system or device - Godot version:
Windows 10
Godot 3 alpha-1
Issue description:
Using the modulo operator in GDScript only works for integers. It should also work for floats.
Steps to reproduce:
Attempting to do the following math results in compilation errors, preventing your app from running
var x = 10.0
var y = 4
print( x % 4)
Can't reproduce on latest master 3a3915b
print( x % 4)
prints 2
Edit: tried on Godot 3 alpha 1 Linux x86_64, no error.
Can you screenshot/copy the compilation error?
My apologies, turns out the issue in particular is that you can not use modulo on floats. In particular I get the error Invalid operands 'float' and 'int' in operator '..'.
whenever I try to use %
on a float
4.0 % 2
and 4.0 % 2.0
will both result in the error Invalid operands for operator
but if it's a variable you won't know until runtime. Either way, modulo on floats is something available in other programming languages, so I see no reason why it shouldn't be available in GDScript
We could make it call fmod
when one or both operands are float
s.
But as long as GDScript is dynamically typed, keeping it only available for int
s at least allows you to be warned about a potential mistake.
So you can cast if computing with the integral part is what you really want or use fmod
if you want to work in the floating point realm.
That also makes your code more explicit and your intent more clear.
it's not a bug, it's a feature (tm),intended to avoids mistakes. Use fmod() for floats.
Note that JavaScript allows the % operator to be used on floats.
I also think it's good to keep as a feature; people complain about duck typing precisely because of such things, so let's not make things more confusing needlessly.
ok, will close this as discussion is exhausted and there is no consense
I know this is a weird problem, but I made a workaround.
How do you do a modulo without a modulo?
Well, here is how it's done:
x = x - y * floor(x / y)
if you think about it, it works in all situations and functions the same way as modulo does.
Well that's the definition of the modulo, so yeah, it works :) But it's simpler to just use the builtin fmod
which does exactly that for you already.
I know this is a weird problem, but I made a workaround.
How do you do a modulo without a modulo?
Well, here is how it's done:
x = x - y * floor(x / y)
if you think about it, it works in all situations and functions the same way as modulo does.
Most helpful comment
it's not a bug, it's a feature (tm),intended to avoids mistakes. Use fmod() for floats.