Disclaimer: I am quite new to working with the bit32 library and bit shifting in general. Bear with me as I attempt to explain what I did.
- It appears the bit32 library uses the no-sign shift operator (>>> instead of >>). How could I use the >> equivalent in Luau?
- In the final example, Lua returns
bit32.rshift(-1, -1) but JS returns
1 for the same equation. Why (JS overflow?)?
It looks like lua fills vacant bits with
I think the best solution for this is to use
bit32.replace(shiftedNum, -1, 31, 31 - shiftAmount) when
num < 0.
So for this example:
bit32.rshift(-1, 0) -- 4294967295
-1 >> 0 -- -1
-1 >>> 0 -- 4294967295
bit32.replace(bit32.rshift(-1, 0), -1, 31, 31 - -1)
bit32.replace(bit32.rshift(-1, 0), -1, 31, 31 - 0)
yield a “trying to access non-existent bits” error.
Maybe I read the documentation wrong, perhaps you need to use a loop instead, but the base premise is to replace bits with a different bit so that a negative number is bit-shifted with 1s instead of 0s
turns out lua just decides that the integer becomes unsigned or something, but this code snippet seems to do the trick:
local function rshiftsigned(num: number, shiftAmount: number)
local shiftedNum = bit32.rshift(num, shiftAmount)
if num < 0 then
return shiftedNum - 2 ^ 32
bit32 library’s functions are only compatible with signed 32 bit integers.
Unless otherwise stated, all functions accept numeric arguments in the range (-251,+251)
To make this work as a left shift, would all you need to do is change bit32.rshift to bit32.lshift?
you should just try it and see
local function alshift(x: number, disp: number): number
local y = bit32.lshift(x, disp)
if y >= 2 ^ 31 then
return y - 2 ^ 32
local function arshift(x: number, disp: number): number
local y = bit32.rshift(x, disp)
if y >= 2 ^ 15 then
return y - 2 ^ 16