Skip to content

Commit

Permalink
try using native bitwise operations without checking lua version
Browse files Browse the repository at this point in the history
  • Loading branch information
jprjr committed Nov 23, 2020
1 parent 47225d0 commit 702a126
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions http/bit.lua
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,26 @@ The bit operations are only done
This means we can ignore the differences between bit libraries.
]]

-- Lua 5.3 has built-in bit operators, wrap them in a function.
if _VERSION == "Lua 5.3" then
-- Use debug.getinfo to get correct file+line numbers for loaded snippet
local info = debug.getinfo(1, "Sl")
return assert(load(("\n"):rep(info.currentline+1)..[[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;
}]], info.source))()
-- Lua 5.1's load function doesn't support reading strings, only
-- functions.
local function string_loader(str)
local sent = false
return function()
if sent then return nil end
sent = false
return str
end
end

-- Lua 5.3+ has built-in bit operators, wrap them in a function.
local info = debug.getinfo(1, "Sl")
local has_bitwise, bitwise = pcall(load(string_loader(("\n"):rep(info.currentline+1)..[[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;
}]]), info.source))
if has_bitwise then return bitwise end

-- The "bit" library that comes with luajit
-- also available for lua 5.1 as "luabitop": http://bitop.luajit.org/
local has_bit, bit = pcall(require, "bit")
Expand Down

0 comments on commit 702a126

Please # to comment.