lua-users home
lua-l archive

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


Am 06.05.2015 um 14:48 schröbte Enrico Colombini:
I was looking for a simple way to make a Lua 5.2 program work with Lua
5.3 too, so I had to select either bit32 or the new native bitwise
operators, depending on the Lua interpreter used.

My first try was a failure:

   -- this will not load on Lua 5.2 because of the '|'
   local bor = bit32 and bit32.bor or function(a, b) return a | b end

So I added a new module:

   file: bitops52.lua
   ------------------------------------------------
   -- cheap Lua 5.2 basic bitwise operators emulation
   -- 2 arguments only (and of course relatively slow)

   return {
       band = function(a, b) return a & b end,
       bor = function(a, b) return a | b end,
       bxor = function(a, b) return a ~ b end,
       bnot = function(a) return ~a end,
       rshift = function(a, n) return a >> n end,
       lshift = function(a, n) return a << n end,
   }
   ------------------------------------------------

and loaded it only when needed:

   local bit32 = bit32 or require('bitops52')

This way, the Lua 5.3-specific operators in 'bitops52' are never seen by
the Lua 5.2 loader and the program works fine with both Lua versions.

Lua 5.3 still includes the bit32 module (at least when compiled with compatibility flags). Also, the latest bit32 backport in the LuaRocks repository compiles for Lua 5.1, 5.2, and 5.3. And last, I think Roberto mentioned that the test suite for Lua 5.3 includes a pure Lua implementation of bit32 if you want to go that route (it's in `bitwise.lua`).

Philipp