[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: The 4 negations of Lua
- From: Russell Haley <russ.haley@...>
- Date: Sat, 17 Sep 2016 23:41:36 -0700
On Fri, Sep 16, 2016 at 11:23 PM, Sean Conner <sean@conman.org> wrote:
> 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.
Hi Sean. My result differed (Lua prompt changed for inline formatting) :
Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
% not 5 == 5
false
% not 5 == 6
false
% not "Mary"=="Mary"
false
% not "Mary"=="mary"
false
This was run on FreeBSD 10.3
Thanks,
Russ
> 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.
>
>