Closed Rathoz closed 3 months ago
I would expect that inject-field error only show up if exact is provided the class annotation
Nope. This is the normal behavior. Basically You can declare class fields in 2 ways:
---@field
---@class
local Foo
is annotated by ---@class
, so you can add fields/methods to this variable and LuaLS will merges added fields into the class Foo
:
---@class Foo
---@field a string -- method1: you declared a string field `a` by `---@field`
local Foo = {}
---@return Foo
function Foo.new() -- method2: you are adding a new()
function field to the class Foo
return {a = 'abc'} -- Pretend this make a proper new object or smt
end
- On the other hand, `---@class (exact)` means that you can only use **method 1** (`---@field`) to declare fields/function/methods of a class. That is if you write `---@class (exact) Foo`, your `function Foo.new` will already throw this `inject-field` warning.
---
A few ways to tackle this warning:
- declare the `bar` field in `---@class Foo`
- Add `---@class` for `foo` (as stated by the warning)
```lua
local function doSomething()
---@class Foo
local foo = Foo.new()
...
end
inject-field
warningThe last one is probably not a good idea, because in this case, LuaLS actually DOES NOT KNOW that Foo
class has the field bar
, and you can't do those goto defintion thing for this field.
Then the docs probably needs to be updated as they state
Marking the class as (exact) means fields cannot be injected after the definition.
With the example used as
---@class (exact) Point
---@field x number
---@field y number
local Point = {}
Point.x = 1 -- OK
Point.y = 2 -- OK
Point.z = 3 -- Warning
I think the example that you quoted from wiki is perfectly fine? It strictly follows the rule "fields cannot be injected after the definition"
x
and y
fields by using the ---@field
annotationPoint.x
and Point.y
=> OKPoint.z
triggers the inject-field
warningIn my own opinion, there is indeed a difference between a class
and an instance
.
---@class
=> this is a class variable and newly injected fields should be merged to class definitionlocal foo = Foo.new()
=> this just returns an instance
of the Foo
class, and generally no extra fields should be allowed to inject into an instance of Foo
class, which will make this variable different from the definition of exiting Foo
class. Unless you explicitly specify that the new variable acts as a class variable. 🤔 Alright, fair.
I still think the documentation should be clarified
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
Based on the wiki https://luals.github.io/wiki/annotations/#class I would expect that
inject-field
error only show up ifexact
is provided the class annotationActual Behaviour
Classes without
exact
getsinject-field
errorReproduction steps
Additional Notes
No response
Log File
No response