[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: The 4 negations of Lua
- From: Sean Conner <sean@...>
- Date: Sat, 17 Sep 2016 02:23:00 -0400
It was thus said that the Great Soni L. once stated:
> Lua has 4 forms of negation:
> Yet only 2 of them can be overloaded.
> It's cool that Lua has 4 forms of negation tho.
'-' is numeric negation. At the CPU level, this is implemented via the
NEG instruction (CPUs that support floating point have a separate
instruction for this). On the x86-64 systems, you can negate 8 bit, 16 bit,
32 bit and 64 bit quantities.
'~' is bitwise negation. This flips each bit of an integer, and is
implemented by the NOT instruction (some CPUs name this COM, for
"complement"---also note that you can't NOT a floating point value).
Also note that for a given integer A:
-A is not equal to ~A 
'not' is boolean negation (in C, this is '!'). Yes, this is synthesized
by the language out of bitwise negation, but with caveats. In C,
is 0, not 0xFFFFFFFB (numeric negation) or 0xFFFFFFFA (bitwise negation).
is 1, not 0x00000000 (numeric negation) or 0xFFFFFFFF (bitwise negation).
This is because of the defintion of a boolean in C. In Lua, 'not', 'and'
and 'or' are defined for booleans:
not a == b
is true if a is not equal to b. Also, because only nil and false are false
not 3 returns false
not nil returns true
not false returns true
not true returns false
is shorthand for
Filling this out:
not == ~=
not < >=
not <= >
not > <=
not >= <
In Lua 5.3, we now have operators for bitwise operations like and, or, xor
and not. These are
& bitwise and
| bitwise or
~ bitwise xor (in context)
~ bitwise not (in context)
 For any system you will probably encounter today. There were
systems where -A does equal ~A, but the chances of coming across
such a system are very slim these days, and probably only in a