[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: RE: An operator syntax for bitfields using metatables
- From: "John Hind" <john.hind@...>
- Date: Sat, 13 Jul 2013 12:28:35 +0100
> -----Original Message-----
> From: John Hind [mailto:email@example.com]
> 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 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
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!