lua-users home
lua-l archive

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


Thomas Lauer writes:
> "Chris Swetenham" wrote:
> > If I am not mistaken, JavaScript has both "null" and "undefined" values; 
> > "undefined" has the same role as "nil" does in Lua, and "null" has the 
> > meaning you suggest. > 
> Similar situation in Perl, where keys in hashes, for instance, can be
> undefined or defined (and queried as such) but still uninitialised.

JavaScript and Perl do differ here.  Perl, like Lua, only has one such value
(called "undef") and that value is similar to Lua "nil".  However, Perl differs
from Lua in that its tables (called "hashes") can still distinguish between a
table containing this nil-like value and the table entry not existing.  This
distinction is internal to the Perl table implementation though.  Perl does not
expose another first-class value.  Rather, the two cases can be differentiated
via a built-in operation called "exists".  This is illustrated below:

  # Perl test suite
  my %t = (x => 1, y => undef);   # note: The key "z" does not exist
  ( $t{x}             ) or die "ASSERT";
  ( not $t{y}         ) or die "ASSERT";
  ( not $t{z}         ) or die "ASSERT";
  ( $t{y} == undef    ) or die "ASSERT";
  ( $t{z} == undef    ) or die "ASSERT";
  ( exists($t{y})     ) or die "ASSERT";  # key "y" exists in table "t"
  ( not exists($t{z}) ) or die "ASSERT";
  print "done\n";

The Perl-like behavior can be simulated somewhat successfully in Lua via
metatables (at least for nil values, not nil keys).  An example of that was
recently added to http://lua-users.org/wiki/StoringNilsInTables ("Existence
Maintained Internally in a Table").