Precedence of power operator
Hi, consider the short code
print(-2**2)
I would expect it prints -4 while it gives 4, meaning that -2**2 equals (-2) ** 2, which is contradict to the common precedence of negate and power (for example, Python and Fortran would print -4).
Is it an expected behaviour?
Yeah, that is because in Rhai uniary operators (such as negation and negative) bind tighter than binary operators...
It would be confusing otherwise:
-2 ** 2 = -4;
-2 * 2 = ? // does - bind tighter than * but no as tight as **?
Binding ** tighter is a relic of math symbols where the index is written literally on top of the base in smaller type, meaning it is not written as a binary operator at all. That makes the interpretation make sense. However, in programming there is no distinction between an index and its base value. So -2 ** 2 is essentially exp(-2, 2).
Okay, would it possible to add a special hint to the document (Rhai book) to clarify this feature, in case someone else would come across this behaviour in the future ?
It's documented pretty well. I can confirm it differs from popular scripting languages, but Rust doesn't have the operator so it doesn't differ from Rust.
IMO it would be better to have an operator precedence table in the Scripting Language section as well, without the numbers and maybe without the directions. They could link to each other. Otherwise the Scripting Language section is a bit incomplete as a language reference.
True. It is certainly missing a section on operators...
It's documented pretty well. I can confirm it differs from popular scripting languages, but Rust doesn't have the operator so it doesn't differ from Rust.
Well, I know that Rust doesn't have it but many other languages have the power operator, and most of them follows the precedence of it in mathematics (for example, in Julia -3^2 == -9). it is not a good idea to change the precedence without explicit descriptions on the tutorials. If you don't wish it bring this surprise to users, a marked sentence to highlight this feature is required in the documents (especially the examples in the "Getting started" section, or examples in playgrounds), instead of making users searching the language dictionary after they come across this surprise.
I think it's worth making this change, because it's a better design.
I just noticed that Rhai has modulus, which is more convenient, and differs from Rust and JavaScript, in a pleasant way. You can page through things by doing n % page_count since negative numbers will return between 0 and n, unlike remainder. It's like this in python.
With the power operator, giving ** higher precedence than - is definitely less surprising.
The current difficulty is thar Rhai's code structure binds unary operators tighter than binary ones...