lua-language-server
lua-language-server copied to clipboard
setmetatable shadowes initialized fields while using a class definition
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?
Diagnostics/Syntax Checking
Expected Behaviour
initialField should be recognized as boolean.
Actual Behaviour
initialField is not recognized.
Reproduction steps

---@class MyClass
local MyClass = {}
function MyClass:new()
---@class MyClass
local myObject = setmetatable({
initialField = true
}, self)
if myObject.initialField then
-- q.e.d.
end
end
Additional Notes
No response
Log File
No response
I'm not sure what you are trying to do here. Are you trying to get the initialField field to show up under MyClass using setmetatable? You can remove the @class annotation to get the inferred type from setmetatable.
If you are trying to assign myObject the MyClass type, add a @field to your MyClass and use @type:
---@class MyClass
---@field initialField boolean
local MyClass = {}
function MyClass:new()
---@type MyClass
local myObject = setmetatable({
initialField = true
}, self)
if myObject.initialField then
-- q.e.d.
end
end
I'm trying to avoid annotation duplication. For instance this works and adds those fields in the class itself, rather than in just the instance inside new:
---@class functional
local fun = { }
function fun:new(state, func, init)
---@class functional
return setmetatable({
_state = state,
_func = func,
_init = init
}, self)
end
return fun
Originally posted by @sumneko in https://github.com/sumneko/lua-language-server/issues/1564#issuecomment-1251882449
So I would expect, that my example would work equivalently.