[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: An operator syntax for bitfields using metatables
- From: Jay Carlson <nop@...>
- Date: Sun, 14 Jul 2013 13:28:57 -0400
On Jul 13, 2013, at 7:28 AM, John Hind wrote:
>> From: John Hind [mailto:john.hind@zen.co.uk]
>
>> 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.)
>
> 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!
More broadly, this is an issue for any immutable type. Consider tuples:
tpl = Tuple(1, 2, 3)
orig_tpl = tpl
assert( tpl[2] == 2 )
tpl[2] = 0 ==> error("that's not really an lvalue")
s = "123"
s[2]="0" ==> error("that's not an lvalue either")
So for __newindex-like-behavior to have any meaning, the assignment had to be syntactic sugar for
tpl = tuple__copy_replacing_index(tpl, 2, 0)
s = string__copy_replacing_index(s, 2, "0")
and note that definitionally tpl~=orig_tpl.
I think this is a scary transformation to do conditionally at runtime. I suppose the answer is to turn *all* t[k]=v statements into sugar; the table implementation doesn't need to copy of course. I'm still scared of it though....
Jay