[Date Prev][Date Next][Thread Prev][Thread Next]
- 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:
<<?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.
----- Original Message -----
> From: "John Hind" <firstname.lastname@example.org>
> To: email@example.com
> Sent: Saturday, 13 July, 2013 1:28:35 PM
> Subject: RE: An operator syntax for bitfields using metatables
> > -----Original Message-----
> > From: John Hind [mailto:firstname.lastname@example.org]
> > 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 -- Extract bit 3 as a boolean.
> > n = true -- Set bit 23.
> > n = not n -- 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
> my idiocy, but no!)
> The problem is that Lua does not honour a return value from the
> 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
> 'newindex' metamethod pretty useless for any other type!
> So unless we patch Lua so this does work as (I, and apparently the
> two) expected, or alternatively implement the bit selection syntax
> this idea is a non-starter. Doing it directly as a syntax patch would
> the advantage that we could do n[10,12] directly rather than by
> 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
> so dot syntax can be used.
> A lesson learned: test your code before trying to sell it!