Skip to content

fix >>> (unsigned right shift) producing wrong results on Lua 5.3+#1703

Open
RealColdFry wants to merge 2 commits intoTypeScriptToLua:masterfrom
RealColdFry:fix/unsigned-right-shift-lua53
Open

fix >>> (unsigned right shift) producing wrong results on Lua 5.3+#1703
RealColdFry wants to merge 2 commits intoTypeScriptToLua:masterfrom
RealColdFry:fix/unsigned-right-shift-lua53

Conversation

@RealColdFry
Copy link
Copy Markdown
Contributor

@RealColdFry RealColdFry commented Apr 1, 2026

https://typescripttolua.github.io/play/#code/5.4/MYewdgzgLgBGMF4YFoCsBuGXs93-BhRxJpZ+AUKJCADYCmAdLSAOYAU8AfDzAAwBKTFgD0ImABYATAE4JMgGwB2WQEZyGzVu2Eq4CHSYsO6nl35DsYmOp137DjXpoNmbdslO9Bw69LmKKjKoQA

TS >>> is a logical right shift (zero-fills from the left), but TSTL was mapping it to Lua's >> which is arithmetic (sign-extends). This gave wrong results for negative numbers: e.g. -1 >>> 0 should be 4294967295 but produced -1.

Fix by masking to unsigned 32-bit first: (left & 0xFFFFFFFF) >> right. The Lua 5.2 (bit32.rshift) and LuaJIT (bit.rshift) paths were already correct.

const n = -5;                                                                                                                
console.log(n >>> 0);   // 4294967291                                                                                              
console.log(1 >>> 0);   // 1                                                                                                       
console.log(-1 >>> 0);  // 4294967295

TS >>> is a logical right shift (zero-fills from the left), but TSTL
was mapping it to Lua's >> which is arithmetic (sign-extends). This
gave wrong results for negative numbers: e.g. -1 >>> 0 should be
4294967295 but produced -1.

Fix by masking to unsigned 32-bit first: (left & 0xFFFFFFFF) >> right.
The Lua 5.2 (bit32.rshift) and LuaJIT (bit.rshift) paths were already
correct.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant