luau
luau copied to clipboard
iterating over any table causes type solver to forget unrelated tables refinements
Consider this code:
--!strict
type Room = {
roomNumber: number,
model: Model,
}
local rooms: {Room} = {}
local latestRoom: Room? = nil
for _, room in rooms do -- line 11
if latestRoom == nil then
latestRoom = room
continue
end
if room.roomNumber > latestRoom.roomNumber then
latestRoom = room
end
end -- line 20
-- We don't want to do anything if we don't have a latest room
if not latestRoom then -- line 23
return
end -- line 25
local players: {{__type: "Player"}} = {}
for _, player in players do
break
end
if true then
print(`Generating room {latestRoom.roomNumber + 1} as latest room had a character`) -- line 33
end
This code produces a type error today:
-- Line 33
TypeError: Value of type 'Room?' could be nil
as the type solver thinks the type of latestRoom on line 33 is Room? (between line 25 and 27 it was of type Room).
Interestingly, this error is caused by the loop done on line 23 to 25! Specifically, removing this code:
-local players: {{__type: "Player"}} = {}
-for _, player in players do
- break
-end
will cause the type solver to function correctly (latestRoom will preserve the type Room, as given by the assert statement).
Clearly this is an error -- this was a completely unrelated loop iteration and should not have affected the type of latestRoom. Note that if I move the loop iteration to a function call instead, the code resolves fine.