lua-users home
lua-l archive

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


2013/7/13 David Burgess <dburgess@gmail.com>:
> FWIW. I like the syntax.
>
> On Sat, Jul 13, 2013 at 1:24 AM, John Hind <john.hind@zen.co.uk> wrote:
>> I've been following the discussion on the bit32 library and share the desire
>> for an operator rather than a functional syntax. However I realised that 99%
>> of my use of this library is for cracking and assembling bitfields for
>> communications protocols and register mapping in embedded systems. 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.
>>

Up to here I like it too.

>> This concept can be extended to extract and replace numeric fields within a
>> larger field (like the bit32 functions with these names). This requires that
>> the index encode two five bit integers which could be done using bitfields
>> within a single number or by using a string index which gets parsed in the
>> metamethod:
>>
>> bitrange = function(s,e) return ((e * 0xFF) + 1) + s end  -- Range testing
>> omitted for clarity
>>
>> nr = n[bitrange(10,15)]  -- Mask out bits 10 through 15 and shift right 10.
>> nr = n[bitrange(15,10)]  -- Mask out bits 10 through 15, shift and reverse
>> the bit order.
>> nr = n[bitrange(12,12)]  -- nr = 1 if bit 12 is set, else 0.
>> b = n[bitrange(12)]      -- b = true only if bit 12 is set (as before).
>> n[bitrange(4,6)] = 2     -- replace bits 4 through 6 with 010.

Here I would prefer string-valued indexing.

nr = n["10:15"]
n["4:6"] = 2

String-valued assignment can be handled too.

n["4:6"] = "010"

The available metamethods for numbers have not been exhausted yet.
What about:

__len  -- number of 1's in n
__call -- iterator over the positions of the 1's in n