各言語でのnot 0やnot nilの値

スクリプト言語では、not演算子がいろいろなタイプのオブジェクトに対して作用するようになっているのがおおい。しかし、not 0やnot nilがどうなるかの仕様はばらばらだったりするので、コードを読むときいつものことだが混乱する。

言語 0 null/nil/None/undef/... その他
ECMAScript false false
php false false
python false false
perl false false for文ではまた別
ruby true false
Lua true false
scheme true true

false/falseになるのは、0をfalseやnullとして使っていたC言語に合わせているからだろうか。

自分で条件式を書く場合は、数値なら != 0や > 0(にあたるもの)はつけるようにしている。nullのほうは、そのまま渡してつけないことが多いかなあ(schemeは別として)。

javascript

print(!0);
if (0) print("0 is true");
print(!null);
if (null) print("null is true");
$ js not0.js
true
true

lua

print(not 0)
if 0 then print("0 is true") end
print(not nil)
if nil then print("nil is true") end
false
0 is true
true

php

<?php
echo !0;
echo "\n";
if (0) echo "0 is true\n";
echo !null;
echo "\n";
if (null) echo "null is true\n";
?>
$ php not0.php
1
1

perl

use strict;
use warnings;

print not 0;
print "\n";
print "0 is true\n" if 0;
print "0 is true at for\n" for 0;
print not undef;
print "\n";
print "undef is true\n" if undef;
print "undef is true at for\n" for undef;
print not ();
print "\n";
print "() is true\n" if (());
print "() is true at for\n" for (());
$ perl not0.pl
1
0 is true at for
1
undef is true at for
1

python

print(not 0)
if 0: print("0 is true")
print(not None)
if None: print("None is true")
$ python not0.py
True
True

ruby

p (not 0)
p "0 is true" if 0
p (not nil)
p "nil is true" if nil
$ ruby not0.rb
false
"0 is true"
true

scheme

(display (not 0))
(newline)
(if 0 (begin
        (display "0 is true")
        (newline)))
(display (not '()))
(newline)
(if '() (begin
          (display "nil is true")
          (newline)))
$ gosh not0.scm
#f
0 is true
#f
nil is true