LuaLS / lua-language-server

A language server that offers Lua language support - programmed in Lua
https://luals.github.io
MIT License
3.12k stars 289 forks source link

Getting a cast warning when it should be fine #2726

Closed gesslar closed 1 week ago

gesslar commented 1 week ago

How are you using the lua-language-server?

Visual Studio Code Extension (sumneko.lua)

Which OS are you using?

Windows

What is the issue affecting?

Type Checking

Expected Behaviour

To not warn me about a type checking when it should be all right.

Actual Behaviour

I am getting a warning

This variable is defined as type `string`. Cannot convert its type to `string|nil`.
- `nil` cannot match `string`
- Type `nil` cannot match `string`

Reproduction steps

While it is true that getSelection() can return nil, I do accommodate for that with my or.

function ThreshCopy:getSelectedText(window, startCol, startRow, endCol, endRow)
  -- Check whether there's an actual selection
  if startCol == endCol and startRow == endRow then return "" end
  local parsed = ""
  -- Loop through each symbol within the range
  for lineNum = startRow, endRow do
    local cStart = lineNum == startRow and startCol or 0
    moveCursor(window, cStart, lineNum)
    local cEnd = lineNum == endRow and endCol or #getCurrentLine() - 1
    selectSection(window, cStart, cEnd - cStart + 1)
    parsed = parsed .. (getSelection(window) or "")
    if lineNum ~= endRow then parsed = parsed .. "\n" end
  end
  return parsed
end

function ThreshCopy:trim(s)
  return s:match("^%s*(.-)%s*$")
end

ThreshCopy.handler = function(event, menu, ...)
  local text = ThreshCopy:getSelectedText(...)
  -- Split the text into lines, trim each line, and handle blank lines separately
  local lines = {}
  for line in text:gmatch("([^\n]*)\n?") do
    if line == "" then
      table.insert(lines, "")
    else
      table.insert(lines, ThreshCopy:trim(line))
    end
  end

  -- Join lines, preserving empty lines as blank lines
  local withoutNewLines = ""
  local previousLineEmpty = false
  for _, line in ipairs(lines) do
    if line == "" then
      withoutNewLines = withoutNewLines .. "\n\n"
      previousLineEmpty = true
    else
      if #withoutNewLines > 0 and not previousLineEmpty then
        withoutNewLines = withoutNewLines .. " "
      end
      withoutNewLines = withoutNewLines .. line
      previousLineEmpty = false
    end
  end

Additional Notes

No response

Log File

No response