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:

  1. Compile and run the following TypeScript code:
    print((new Map<number, any>()).has(null)); 
    
  2. Actual result: Prints true
  3. Expected result: Should print false as 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:

  • lastKey is initialized to nil
  • When checking key = nil, lastKey == nil returns true
  • This causes .has(null) to incorrectly return true

Proposed Fix:

  1. Add a dedicated hasNil flag in the Map class to track the presence of nil keys
  2. Modify the has method:
    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
    
  3. Update set/delete methods to maintain hasNil state:
    • In set: Set hasNil = true when key == nil
    • In delete: Set hasNil = false when deleting a nil key

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)

Most upvoted comments

@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.)