lua-users home
lua-l archive

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


Rici wrote:

> Of course, the truth value of the expression is correctly
> computed, but the statement in the reference manual that
> it always returns 'true' or 'false' is not 6 :)

I definitely read that sentence in the reference manual
multiple times to make sure I wasn't missing something.

> On the other hand, I've never really liked that 'not not'
> idiom.  Coercing to a boolean should never really be
> necessary imho.

I can imagine writing a function and wanting it to hide
internal information; maybe the first implementation returns
some number or nil but a later implementation is projected
to return some string or nil; having the function return
true or false future-proofs it (and is more elegant than
returning true or nil).

In other words, writing "return not not foo" is nicer than
writing "if foo then return true else return false end".

In the case where we originally found this, though, a
colleague was working around a callback handler (since
fixed) that required a boolean.

Just for kicks, the luac -l output for "print(not not (42 +
42))" is

main <stdin:0> (6 instructions, 24 bytes at 0x804bc98)
0 params, 2 stacks, 0 upvalues, 0 locals, 2 constants, 0 functions
        1       [1]     GETGLOBAL       0 0     ; print
        2       [1]     ADD             1 251 251       ; 42 42
        3       [1]     NOT             1 1 0
        4       [1]     NOT             1 1 0
        5       [1]     CALL            0 2 1
        6       [1]     RETURN          0 1 0

The output for "print(not not (42 or 42))" is

main <stdin:0> (7 instructions, 28 bytes at 0x804bc98)
0 params, 2 stacks, 0 upvalues, 0 locals, 2 constants, 0 functions
        1       [1]     GETGLOBAL       0 0     ; print
        2       [1]     LOADK           1 1     ; 42
        3       [1]     TEST            1 1 1
        4       [1]     JMP             0 1     ; to 6
        5       [1]     LOADBOOL        1 1 0
        6       [1]     CALL            0 2 1
        7       [1]     RETURN          0 1 0

-- 
Aaron