lua-users home
lua-l archive

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

Hi Thomas,

> sorry to be such a nuisance... but I think the newly posted code
> (thanks!) has another small error (discovered late last night so I
> didn't want to post w/o further checking).
> Look at these lines in unpickle():
> >   if t == TNIL then
> >     return nil, 2
> __________________^
> >   elseif t == TBOOLEAN then
> >     return unpack("B", o, p) == 1, 3
> _____________________________________^
> I think they should read:
> >   if t == TNIL then
> >     return nil, p
> >   elseif t == TBOOLEAN then
> >     return unpack("B", o, p) == 1, p+1 -- as "B" consumes 1 byte
> (i.e. this shouldn't return a numerical 2 (or 3) but p (or p+1)).

Right, thanks for spotting this! Bug reports are never a nuisance. :)

> I am not sure that the TNIL case can ever be executed... as tables can't
> contain nil values, by definition. It's of course possible to call
> "pickle(nil)", so perhaps it should remain in there.

It's there just for the sake of completeness. However, there might be cases in
which you want to build a custom pickler to store tables with a known
structure (in case you have many of these tables and don't want to waste file
space storing the keys, say): 

mypickler = function(mystruct)
  return {
    P = function(t, fname)
      local f =, "w")
      for i in ipairs(mystruct) do
    U = function(fname)
      local f =
      local o = f:objects()
      local m = {}
      for _, k in ipairs(mystruct) do
        m[k] = o()
      return m

And some values might be nil:

Lua 5.1.2  Copyright (C) 1994-2007, PUC-Rio
> p = mypickler{"a", "b", "c"} --> this could also be pickled :)
> p.P({true, "hello", math.pi}, "abc.mystruct")
> table.foreach(p.U"abc.mystruct", print)
a       true
c       3.1415926535898
b       hello
> p.P({1, nil, function() end}, "abc.mystruct")
> table.foreach(p.U"abc.mystruct", print)
a       1
c       function: 0x30a390

I've updated the pickler code with your suggestions and a few changes, and
it's now in version 0.2. I can post it later (wiki?) if there's enough
interest, or send the code privately.


A mathematician is a device for turning coffee into theorems.
        -- P. Erdos 

Luis Carvalho
Applied Math PhD Student - Brown University
PGP Key: E820854A <>