lua-users home
lua-l archive

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


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.

--
  Enrico