[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
**Subject**: **Re: Operator precedence and unary minus**
**From**: Tim Hill <drtimhill@...>
**Date**: Mon, 21 May 2018 14:53:59 -0700

> On May 21, 2018, at 1:47 PM, Egor Skriptunoff <egor.skriptunoff@gmail.com> wrote:
>
> Hi!
>
> In most programming languages (and in Lua too) unary minus has higher priority than group of multiplicative operators ( * / % ).
> It usually doesn't cause any problems due to "commutativity" between negation and any multiplicative operator in most programming languages:
> (-a) * b == - (a*b)
> (-a) / b == - (a/b)
> (-a) % b == - (a % b)
> As you can see, precedence of unary minus actually doesn't matter when only basic arithmetic operators are involved ( + - * / % ).
> We can write (...-a%b) without worrying about precedence of binary / unary minus.
>
> But Lua is special.
> Lua has mathematically correct modulo operator (and that's great !).
> The problem arises because in Lua negation operator is "not commutative" with modulo:
> (-a) % b ~= - (a%b)
>
> That's why in Lua we have an unpleasant surprise:
> - a%m - b%n ~= - b%n - a%m
> It's looks very weird.
> That should be an equality as in all other programming languages.
>
> I think it would be good to lower the priority of unary minus in Lua.
> For example, unary minus may have the same priority as binary minus.
> What do you think about it?
>
> BTW, the same problem exists for // operator.
>
> -- Egor
You really dont want to alter precedence if unary minus. As others have noted, it’s going to break LOTS of code. It also introduces very strange effects with literal negative numbers, especially when you have metamethods involved.
—Tim