|
Am 10.07.2013 21:45 schröbte Rena:
On 2013-07-10 5:14 AM, "Philipp Janda" <siffiejoe@gmx.net> wrote:On 09/07/2013 20.23, Ico wrote:val = val & ~mask for clearing bits in a word. Doing this with bit32 does not result in code that is more readable, IMHO: val = bit32.band(val, bit32.bnot(mask))I usually use `val = val - mask` for this, meaning "clear all bits set inmask from val". I also use `a + b` for `a | b`, and `a( b )` for `!(b & ~a)` (i.e.: check if the set of one-bits in b is a subset of one-bits in a). Together with `==` this is enough to implement the common bit flags in C APIs.These aren't the same though. Addition and subtraction will give incorrect results if not all bits are clear/set. This can be an issue with flags:
I know. This was only a syntax example what is possible right now if you don't insist on using numbers for bit operations. I use (and will continue to use) different types of userdata for my flags, because I want the extra type safety: I don't want anyone to mix flags from different options, or even put an arbitrary number in there. The operations are implemented as bit operations as shown above. See here[1], and here[2], how they are defined on the C side ...
[1]: https://github.com/siffiejoe/prg-buildsh/blob/master/src/ape_flag.h[2]: https://github.com/siffiejoe/prg-buildsh/blob/master/src/ape_file.c#L28
On the Lua side it's -- combine flags local flags = ape.FPROT_UREAD + ape.FPROT_UWRITE + ape.FPROT_UEXECUTE -- remove a flag flags = flags - ape.FPROT_UEXECUTE -- test for flag if flags( ape.FPROT_UWRITE ) then ... end -- type safety: local wrong = ape.FOPEN_CREATE + ape.FILE_ATTR_READONLY--> test.lua:16: bad argument #2 to '__add' (apr_oflags_t expected, got apr_fileattrs_t)
Philipp