Nullable / optional tuple

Type-checking question here: what is the proper way to write a nullable / optional tuple?

Ex.:

-- Returns the nearest player to `part` and the distance between them,
-- IF there is a player's character
local function getNearestPlayer(part: Part)
    local nearestPlayer = nil
    local smallestDistance = math.huge

    -- algorithm for finding the nearest player...

    -- finished.
    -- at this point, if no players were found, `nearestPlayer` remains nil
    -- and `smallestDistance` is still `math.huge`
    -- so the function's return should be either the tuple `(Player, number)`
    -- or `nil`.
    -- ideally, I should be able to do `(Player, number)?` or maybe
    -- `(Player, number) | nil`, but the closest I can find is `(Player?, number?)`
    -- but there's some obvious issues.
end

This feels more like a feature request, but whatever. Just in case somebody faces the same little issue (or for future me).

1 Like

(Player?, number?) is your best option. The type-checker isn’t able to know that if the Player object is nil, so too will be the returned number, especially from calling code’s perspective. Calling code will still need to check that both the Player and the number returns exist before they can acted upon without getting warnings from the linter. You could wrap the results in a table to coalesce it into a single object, but that’s not really worth the runtime overhead just to appease the type-checking system.

As described, though, your function would always return a number, just not a particularly useful one in the case where no player is found. If you don’t plan to discard the distance, then wouldn’t the results always be (Player?, number)?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.