LuaLS / LuaLS/lua-language-server

Break in loop makes variable go out of scope early?

Open
#2,912 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Lua
Stars
4.4k
Forks
442
PR merge metrics
No merged PRs in 30d

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal Lua reproduction in the issue and inspect type-checking behavior around the local a, the for loop, and break. Done means a retains its A type after the loop and the ---@cast a A line is no longer reported as unknown; add a regression test using this reproduction.

Written by the indexing model from the issue text.

Assessment

Tech stack
lua
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
50/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.