[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: RE: lua-l Digest, Vol 36, Issue 54
- From: "John Hind" <john.hind@...>
- Date: Tue, 16 Jul 2013 12:16:25 +0100
> Date: Tue, 16 Jul 2013 02:16:13 +0100 (BST)
> From: Robert Virding <email@example.com>
> 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
> Date: Mon, 15 Jul 2013 22:58:57 -0300
> From: Luiz Henrique de Figueiredo <firstname.lastname@example.org>
> Given these strings it easy to parse them into a Lua table containing
> the names and starting and end points of the bitfields described there.
> That table can then be used to set index and newindex metamethods for
> get and put the bitfields using Lua syntax, or perhaps pack and unpack
Yes, having thought some more about this, the use of 'newindex' is pretty
much a non-starter with number bitfields (or string bitfields for that
matter). The bitfield would have to be represented by a table or a userdata
(this would also allow variable length, and arbitrarily long bitfields
I still think there is mileage in index and/or call syntax for accessing
bits in number bitfields:
b1 = n1 -- extract bit 20 as a boolean (index metamethod)
n2 = n1(20,23) -- extract bits 20 through 23 as a number 0..15 (call
n2 = n1(20) -- extract bit 20 as a number 0 or 1 (call metamethod)
The advantage being that bit positions can be variables.
However, I agree a "bitfield assembler" is the best way to go for
I was thinking of a simple "bitfield map" based on a string with a character
per bit position:
map = "aaa11Bcccc0DE" -- 0 and 1 are literal, lowercase placeholder for
number, uppercase for boolean.
n1 = tobitfield(map, 4, false, 14, true, false)
n1 = tobitfield("101110010") -- This syntax also gives us binary constants!
n2, b1, n3, b2, b3 = frombitfield(map, n1)
n3 = frombitfield(map, n1, "c")
b1, b2 = frombitfield(map, n1, "BD")
I would also have a mapless form of the tobitfield function:
n1 = tobitfield(true, false, 4, true, 6, 3)
The first number of a pair, or a number on its own, advances to that bit
position filling with 0 as necessary, the second number in a pair is
inserted as a binary value. To insert a field followed by other values, you
need a three number sequence: the starting bit number, the value, the bit
number after the last bit in the field.