lua-users home
lua-l archive

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


On Mon, May 11, 2009 at 2:41 AM, steve donovan wrote:
> pretty.write is currently irritating me, and
> I'm trying for something really pretty, like:
> {
>  {1,2,3},
>  {3,4,5}
> }
>

There's many ways to do this [1], and its likely not possible to
satisfy everyone with just one function.  As the differing
implementations in Lua Gems 3 and 4 show, the main use cases are
debugging and serialization.  I find debugging the more common case,
and the easier case, where an off-the-shelf function will do.  Still,
there may be little reason not to allow the debugging implementation
to also be usable for basic serialization if need be (unlike Lua Gem
3).

The change proposed above is like going from Perl's Data::Dumper (part
of the Perl core) to Data::Dump [2-3].

  $ perl -e 'use Data::Dumper; $x = {a=>1, b=>2}; print Dumper($x)'
  $VAR1 = {
            'a' => 1,
            'b' => 2
          };

  $ perl -e 'use Data::Dump qw(dump); $x = {a=>1, b=>2}; print dump($x)'
  { a => 1, b => 2 }

Unlike the current pretty.write, both of these handle cycles though:

  $ perl -e 'use Data::Dumper; $x = {}; $x->{a}=$x; print Dumper($x)'
  $VAR1 = {
            'a' => $VAR1
          };

  $ perl -e 'use Data::Dump qw(dump); $x = {}; $x->{a}=$x; print dump($x)'
  do {
    my $a = { a => 'fix' };
    $a->{a} = $a;
    $a;
  }

The implementation may be useful for comparison [4].

The Lua equivalents of both of those would be respectively

  -- Data::Dumper-like
  var1 = {}
  var1.a = var1

  -- Data::Dump-like
  (function()
    local a = {}
    a.a = a
    return a
  end)()

I like the latter Data::Dump-like approach since the return value
always represents a single expression, which is a table in the simple
case (as desired) or an anonymous function call in the general case.
As mentioned, it also has the property that dump("foo") == "foo".

BTW, the name "pretty.write" is similar to io.write and suggests
writing to a file or standard output, when it actually returns a
string.  I suggest pretty.dump.

[1] http://lua-users.org/wiki/TableSerialization
[2] http://search.cpan.org/~ilyam/Data-Dumper
[3] http://search.cpan.org/~gaas/Data-Dump
[4] http://cpansearch.perl.org/src/GAAS/Data-Dump-1.14/lib/Data/Dump.pm