TypeScriptToLua: Bug: `Map.prototype.has(null)` returns true for empty Map
Title: Bug: Map.prototype.has(null) returns true for empty Map
Description:
When calling .has(null) on an empty Map, it incorrectly returns true, contrary to standard TypeScript behavior where it should return false.
Steps to Reproduce:
- Compile and run the following TypeScript code:
print((new Map<number, any>()).has(null)); - Actual result: Prints
true - Expected result: Should print
falseas per standard TypeScript behavior
Playground Link:
https://typescripttolua.github.io/play#code/5.4/A4JwlgdgLgFDEFMDuACAsgQ2AHklBA5giADQoYQCeAfDAJR0B0AFhgM7wCuANtw0A
Root Cause:
The current Lua implementation of Map.prototype.has:
function Map.prototype.has(self, key)
return self.nextKey[key] ~= nil or self.lastKey == key
end
In an empty Map:
lastKeyis initialized tonil- When checking
key = nil,lastKey == nilreturnstrue - This causes
.has(null)to incorrectly returntrue
Proposed Fix:
- Add a dedicated
hasNilflag in the Map class to track the presence ofnilkeys - Modify the
hasmethod:function Map.prototype.has(self, key) if key == nil then return self.hasNil end return self.nextKey[key] ~= nil or (self.lastKey ~= nil and key == self.lastKey) end - Update
set/deletemethods to maintainhasNilstate:- In
set: SethasNil = truewhenkey == nil - In
delete: SethasNil = falsewhen deleting anilkey
- In
This approach correctly handles the null case while maintaining compatibility with existing functionality.
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 17 (8 by maintainers)
@Zamiell Never mind, I don’t intend to forcefully prove that I am correct. It’s just that I encountered this issue and raised it. As for whether you fix it or not, that’s up to your consideration. Map.prototype.has(nil) returning true always feels a bit odd to me. (No need to reply to me, you’ve actually made it quite clear, thanks.)