[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: An operator syntax for bitfields using metatables
- From: Robert Virding <robert.virding@...>
- Date: Tue, 16 Jul 2013 02:16:13 +0100 (BST)
While operators for bit-fields are very useful I think a better way is a syntax which allows you describe/build the whole bitstring in one go. We have this in Erlang and it makes building/pulling apart protocol packets very much easier and clearer. Some simple examples of the top of my head:
64-bit IEEE floating point:
<<Sign:1,Exponent:11,Mantissa:52>>
IP datagram:
<<?IP_VERSION:4, HLen:4, SrvcType:8, TotLen:16,
ID:16, Flgs:3, FragOff:13,
TTL:8, Proto:8, HdrChkSum:16,
SrcIP:32, DestIP:32, RestDgram/binary>>
The second one is a bit longer than 32 bits. :-) I think you get the idea. We can also use the same syntax for pulling apart the binary/bitstring. This really is powerful and simplifies a lot of things and I think that something similar would be useful for Lua if you seriously intend to work with bitfields.
Robert
----- Original Message -----
> From: "John Hind" <john.hind@zen.co.uk>
> To: lua-l@lists.lua.org
> Sent: Saturday, 13 July, 2013 1:28:35 PM
> Subject: RE: An operator syntax for bitfields using metatables
>
> > -----Original Message-----
> > From: John Hind [mailto:john.hind@zen.co.uk]
> > Sent: 12 July 2013 16:25
>
>
> > It is straightforward to add a syntax for this in
> > a C library by providing a metatable for the number type with
> > 'index'
> > and 'newindex' metamethods. Then:
> >
> > b = n[3] -- Extract bit 3 as a boolean.
> > n[23] = true -- Set bit 23.
> > n[6] = not n[6] -- Toggle bit 6.
> >
>
> Arghh! This does not work! (But I still think it should.)
>
> (Phew! I feared David Burgess and/or my old nemesis Dick Laurie had
> spotted
> my idiocy, but no!)
>
> The problem is that Lua does not honour a return value from the
> 'newindex'
> metamethod so the second and third lines in the above example do not
> actually change n. This is fine for tables and userdata, but makes
> the
> 'newindex' metamethod pretty useless for any other type!
>
> So unless we patch Lua so this does work as (I, and apparently the
> other
> two) expected, or alternatively implement the bit selection syntax
> directly,
> this idea is a non-starter. Doing it directly as a syntax patch would
> have
> the advantage that we could do n[10,12] directly rather than by
> bitfield
> encoding or string parsing, but I still think the operation of the
> metamethod should be also changed to make it usable for all types (a
> non-breaking change if nil return is interpreted as 'silently do
> nothing' as
> at present).
>
> Dick: if using a string key, it is neat to have something like
> "bit_4_to_12"
> so dot syntax can be used.
>
> A lesson learned: test your code before trying to sell it!
>
>
>
>