lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Soni L. once stated:
> Lua has 4 forms of negation:
> 
> -
> ~
> not
> ~=
> 
> 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 [1]

  'not' is boolean negation (in C, this is '!').  Yes, this is synthesized
by the language out of bitwise negation, but with caveats.  In C, 

	!5

is 0, not 0xFFFFFFFB (numeric negation) or 0xFFFFFFFA (bitwise negation). 
Conversely,

	!0

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
in Lua:

	not 3		returns false
	not nil		returns true
	not false	returns true
	not true	returns false

Also,

	~=

is shorthand for

	not ==

  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)

  -spc

[1]	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
	museum.