Skip to content

setmetatable shadowes initialized fields while using a class definition #1575

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
sewbacca opened this issue Sep 21, 2022 · 2 comments
Closed
Labels
enhancement New feature or request
Milestone

Comments

@sewbacca
Copy link
Contributor

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

grafik

---@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

@carsakiller
Copy link
Collaborator

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

@sewbacca
Copy link
Contributor Author

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 #1564 (comment)

So I would expect, that my example would work equivalently.

@sumneko sumneko added the enhancement New feature or request label Sep 22, 2022
@sumneko sumneko added this to the 3.6.0 milestone Sep 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants