lua-users home
lua-l archive

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

On 09/07/2013 20.23, Ico wrote:
* On Tue Jul 09 20:02:48 +0200 2013, Jerome Vuarand wrote:

We are considering adding bitwise operations to Lua. After all, the main
reason Lua did not have them was that they were awkward as primitive
operations over floating-point numbers. With integer numbers, this
problem is gone.

In other words it feels a little too low level (like the goto
feature), and the overlap with C, which Lua complements so well, may
compromise some of the uniqueness of Lua.

It probably very much depends on the type of application and programmer.

People who regularly use bit operation probably do so in a language
where native operators are available (i.e. C), and chances are they are
familiar with the various idioms, for example

   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.bnot(mask))

For a user not familiar with bit operations both probably look as
confusing, but the first at least feels more natural to those who *are*
regularly using binary operators in other languages.

I must agree with you. Although I don't need bitops so much, I find them useful from time to time. What I really hate is functional notation for them: any time you try to do little-more-than-trivial stuff you end up with ugly code (from a readability POV).

Infix notation is really a must for writing readable, straightforward code using bitops IMHO. I'm not particularly fond of C-like operators, so I wouldn't object to a more luaish keywords-based approach. Moreover you cannot have exactly the same operators as in C, since ^ is already taken, so you would have to choose something else for XOR and this could lead to interferences for programmers switching to/from C (~= is enough for that :-).

The only problem I see is choosing good keywords, since *and*, *or* and *not* are already taken.

Random thoughts:

band, bor, bxor, bnot, rshift, lshift
_and_, _or_, _xor_, _not_, _rshift_, _lshift_
And, Or, Xor, Not, Rshift, Lshift

Probably people who often use bitops should try to recast some common idioms using those (and other) alternatives and see what looks best.

val = val And Not mask
val = val _and_ _not_ mask
val = val band bnot mask
val = val AND NOT mask
val = val and_ not_ mask
val = val _and _not mask
(Using a sigil to avoid breaking old code - ugly maybe...)
val = val @and @not mask

Of course if more operators are introduced the question arises whether more metametods are needed as well (do we need to "overload" bitops for tables?).

As for me: I'm using Lua a lot for pretty low level embedded targets,
and having bitops would make my code cleaner and my life a bit easier.


-- Lorenzo

()  ascii ribbon campaign - against html e-mail
/\   - against proprietary attachments