为什么要使用 `not not` 操作符?

在以下Lua代码中:

function eq_event(op1, op2)
    if op1 == op2 then
        return true
    end
    local h = getequalhandler(op1, op2)
    if h then
        return not not h(op1, op2)
    else
        return false
    end
end

为什么在返回值前要使用 not not?它和原始的返回值有什么区别?我还记得在C语言中,有时也会在某些表达式前使用 !!,它们是一样的吗?

点赞
用户320615
用户320615

not not 运算会将 nil 转换为 false,将除 false 以外的所有其他值转换为 true。在与 C 交互时,可能需要仅返回布尔值。

是的,这与 C 中的 !! 相同。唯一的区别是在 C 中,值为 0(和某些我不记得的其他值)也是假值(即,当进行双重否定运算时将返回 false)。

2012-08-04 05:55:52