Skip to content

Instantly share code, notes, and snippets.

@noaccessl
Last active April 8, 2025 15:04
Show Gist options
  • Select an option

  • Save noaccessl/76efe3edf15507c4f1652975d3a8befb to your computer and use it in GitHub Desktop.

Select an option

Save noaccessl/76efe3edf15507c4f1652975d3a8befb to your computer and use it in GitHub Desktop.
Bitwise operators in GLua

Implementation of bitwise operators in GLua

Just for variety.

As for performance, it's obviously slower, but not that much.

image

With JIT it's somehow faster sometimes.

Demo

print( (1) '<<' (0) ) -- 1
print( (1) '<<' (1) ) -- 2
print( (1) '<<' (2) ) -- 4

local flags = (2) '|' (4, 8, 256, 512)

if ( flags '&' (512) ~= 0 ) then
	print( 'flag 512 is set' )
end
local lshift = bit.lshift
local rshift = bit.rshift
local bor = bit.bor
local band = bit.band
local numberToManipulate
local function operator_lshift( shiftCount )
return lshift( numberToManipulate, shiftCount )
end
local function operator_rshift( shiftCount )
return rshift( numberToManipulate, shiftCount )
end
local function operator_bor( ... )
return bor( numberToManipulate, ... )
end
local function operator_band( ... )
return band( numberToManipulate, ... )
end
debug.setmetatable( 0, {
__call = function( thisNumber, operator )
numberToManipulate = thisNumber
if ( operator == '<<' ) then
return operator_lshift
elseif ( operator == '>>' ) then
return operator_rshift
elseif ( operator == '|' ) then
return operator_bor
elseif ( operator == '&' ) then
return operator_band
end
end;
} )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment