lua-users home
lua-l archive

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


2012/11/23 Rena <hyperhacker@gmail.com>:

> I once hacked up some metatable magic to allow writing
> pseudo-infix operators like:
>
> x = ((4) '<<' (3)) '|' (y)
>
> It's ugly and inefficient, but it works! Probably biggest drawback is
> not only the operators need to be quoted (since they're strings), but
> the parameters need to be in parentheses (since they're either being
> called or being function arguments), so it becomes bracket hell
> quickly...
>
> Really love to have real bit operators in Lua.

I did something along the same lines sometime last year, but
with a different approach. I could not resist improving it a little.
The equivalent of the above code would be

  b32=require"b32op"
  x =  b32(4)/-3 + y

Explanation: b32 wraps a 32-bit value in a table. `/` means
rshift, `+` means bor. The left operand of an operator that
expects two 32-bit values must already be a b32, the right operand
may be a number.

There's some support for using 32-bit values as sets:

  s = b32.set(3,5,8)
  for k in b32.members(s) do print(k) end
3
5
8

Also, the logical operations have been redefined so __le means
set inclusion etc.

Attachment: b32op.lua
Description: Binary data