LuaLS / LuaLS/lua-language-server
Ipairs with generic
Open
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?
Windows
What is the issue affecting?
Annotations
Expected Behaviour
Should have got a correct type inference in a generic function.
Actual Behaviour
- could not specify a
V-related type forresultin the generic function ipairswill be inferred asunknown- returns of the generic function will be inferred as a strange type
Reproduction steps
---@class Test
---@field name string
---@type Test[]
local tests = {
{ name = "test1" },
{ name = "test2" },
{ name = "test3" },
}
--[[
CORRECT:
function group_by(rows: <V>[], key: string)
-> table<string, <V>[]>
]]
---@generic V
---@param rows V[]
---@param key string
---@return table<string, V[]>
local function group_by(rows, key)
--[[
---@type table<string, V[]>
GOT: Undefined type or alias `V`.
]]
local result = {}
-- WRONG: local v: unknown
for i, v in ipairs(rows) do
local k = v[key]
if not result[k] then
result[k] = {}
end
table.insert(result[k], v)
end
return result
end
--[[
WRONG:
local groups: table<string, <V>[]> | { [<K>]: Test }
EXPECTED:
local groups: table<string, Test[]>
]]
local groups = group_by(tests, "name")
Additional Notes
No response
Log File
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the Lua snippet from the issue and inspect the language server's generic annotation, indexed-access, and ipairs type-inference paths. Done means V is accepted in the local result annotation, ipairs yields the generic element type, and group_by(tests, "name") is inferred as table<string, Test[]>.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- lua
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100