lua-users home
lua-l archive

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


It was thus said that the Great Coda Highland once stated:
> On Wed, Nov 19, 2014 at 5:06 PM, Sean Conner <sean@conman.org> wrote:
> >
> >   I'm looking over string.pack() and string.unpack() in Lua 5.3, and I have
> > a few questions:
> >
> > 1.  Why is string.unpack(fmt,s[,pos]) instead of string.unpack(s,fmt[,pos])?
> >     This means I can't do:
> >
> >                 magic,timestamp,tag = raw:unpack("I4I4I4")
> >
> >     Instead, it's:
> >
> >                 magic,timestamp,tag = string.unpack("I4I4I4",raw)
> >
> >     This also means I may have to cache the string table in a local variable
> >     in a module when it might be avoided.   The former also "reads" better
> >     to me.
> 
> The rationale is because most functions (e.g. printf) take their
> format strings as the first parameter.
> 
> Why not ("l4l4l4"):unpack(raw)? 

  The joke answer is:  I want 4-byte unsigned integers, not an invalid
format trying to unpack native longs.

  I suppose you could also do:

	packetlayout = "I4I4I4"

	magic,timestamp,tag = packetlayout:unpack(raw)

	-- elsewhere in the code

	raw = packetlayout:pack(MAGICCOOKIE,os.time(),myid)

  which I could live with (DRY [1] and all that).  

  -spc

[1]	Don't Repeat Yourself