Luau for loop type checking

I’m sure I’m simply misunderstanding how type checking works but I have this function here:

local function collgroup(model: Model)
    for i : number, v : BasePart in pairs(model:GetDescendants()) do
        v.CollisionGroup = 'nocollision'
    end
end

My issue is that this script still allows for instances other than BaseParts to pass through the for loop.

I’m aware that I could easily just do:

local function collgroup(model: Model)
    for i : number, v : BasePart in pairs(model:GetDescendants()) do
        if v:IsA('BasePart') then
            v.CollisionGroup = 'nocollision'
        end
    end
end

but I want to at least understand how the type checking works.

Thanks!

1 Like

if that happens, then the type of v has to be Instance. It can only be BasePart if you are absolutely sure that all decendants of model are BaseBarts.

The descendants’ array has the type {Instance}, so instead of typing v with BasePart, you should use Instance.

Once you pass the if v:IsA("BasePart") part, the type for v will then be refined to BasePart inside that scope.

Type checking doesn’t effect runtime, it just helps you navigate your code better. (And will soon help the compiler run faster)

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