lua-users home
lua-l archive

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


> -----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!