Skip to content

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

Merged
Perryvw merged 2 commits intoTypeScriptToLua:masterfrom
RealColdFry:fix/unsigned-right-shift-lua53
Apr 3, 2026
Merged

fix >>> (unsigned right shift) producing wrong results on Lua 5.3+#1703
Perryvw merged 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.
@Perryvw Perryvw merged commit 5176fcd into TypeScriptToLua:master Apr 3, 2026
5 checks passed
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.

2 participants