-
Given the following code snippet: ---@class Pc
local Pc = {}
Pc.__index = Pc
local function initDbData(self, dbData)
self.aa = dbData.aa -- inject-field warning here, I want to ALLOW it and let LuaLs merge this field to `Pc` class
self.bb = dbData.bb -- inject-field warning here, I want to ALLOW it and let LuaLs merge this field to `Pc` class
end
function Pc.new(dbData)
---@class Pc
local self = setmetatable({}, Pc)
self.a = 1
self.b = 2
initDbData(self, dbData)
return self
end
I can think of 3 ways, but all of them seems to have pros and cons method 1
local function initDbData(self, dbData)
---@class Pc
self = self
self.aa = dbData.aa -- now will be no inject-field warning
self.bb = dbData.bb -- now will be no inject-field warning
end But this looks very silly... as it is not pure annotation statement. And in the worst case some day another person may think that this is a useless statement and want to remove it 😅 method 1.1
local function initDbData(pcObject, dbData)
---@class Pc
local self = pcObject
self.aa = dbData.aa -- no inject-field warning as well
self.bb = dbData.bb -- no inject-field warning as well
end
method 2
---@class Pc
---@field aa any
---@field bb any
method 3
function Pc:_initDbData(dbData)
self.aa = dbData.aa -- no inject-field warning now
self.bb = dbData.bb -- no inject-field warning now
end
function Pc.new(dbData)
...
self:_initDbData(dbData)
return self
end
|
Beta Was this translation helpful? Give feedback.
Answered by
tomlau10
Jun 21, 2024
Replies: 2 comments 5 replies
-
I think you want to do something like this right? ---@class (exact) Pc
---@field __index table
---@field new fun(dbData: table):Pc
local Pc = {}
Pc.__index = Pc
---@param self Pc
---@param dbData table
local function initDbData(self, dbData)
self.aa = dbData.aa -- inject-field warning
self.bb = dbData.bb -- inject-field warning
end
function Pc.new(dbData)
---@type Pc
local self = setmetatable({}, Pc)
self.a = 1
self.b = 2
initDbData(self, dbData)
return self
end |
Beta Was this translation helpful? Give feedback.
4 replies
-
使用继承, 让Pc继承基类 |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
不是太明白,繼承哪個基類? dbData嗎?
就是不能說直接做
---@class Pc: PcDbData
PcDbData
base class不就需要手動對
PcDbData
加---@field
了?這個有點像我最初提到的 method 2 所引伸出的問題
我是想做到一了百了,自動 infer 出新字段
而不需要每次加新字段,就得手動加1個
---@field
暫時來說可能是用 method 3 🤔