LuaLS/lua-language-server

Break in loop makes variable go out of scope early?

Opened this issue · 1 comments

How are you using the lua-language-server?

Visual Studio Code Extension (sumneko.lua)

Which OS are you using?

Linux

What is the issue affecting?

Type Checking

Expected Behaviour

I was trying to fetch a table that could be within a number of tables. Leaving early if it was found

I wanted that locally scoped variable to be the same type after the loop as before it

Actual Behaviour

Only for my variable scoped outside the loop to be unknown after it.
In an attempt to band-aid what I originally luals choking a little, I tried casting it. Only to find it was in fact unaware it even existed.

Reproduction steps

As minimal I can get the code to be and reproduce it:

---@type {[any]:A}
local T

function F()
    ---@class A
    local a

    for _, i in pairs{} do
        a = T[1]
        if a then break end
    end

    -- See it complain the `a` variable
    ---@cast a A
end

Additional Notes

No response

Log File

service.log

In an attempt to band-aid what I originally luals choking a little, I tried casting it. Only to find it was in fact unaware it even existed.

There is another strange bug that existed for a while. When you use @cast on a variable which has no more access to it later, it will complain unless the file has a trailing newline (yeah~ strange 🙈 )
see: #2326

  • this WILL complain
do
    ---@class A
    local a
    ---@cast a A
end -- no trailing new line
  • this WILL NOT complain
do
    ---@class A
    local a
    ---@cast a A
end
-- add trailing new line here