--- my supper class ---@class Transport local p = Class()
--- 子类 ---@class Car : Transport local cls = Class(p) function c:test() end
其格式如下:
1
--@class my_type[: parent_type] [@comment]
举个例子:
1 2 3 4
---@class Car : Transport @define class Car extends Transport local cls = class() function clas:test() end
上面定义了一个Car类,我们可以使用@type Car来表明某个变量属于Car类
变量的声明
使用@type可以指明某个变量的类型
1 2 3 4 5
---@type Car local car1 = getCar() ---@type Car global_car = getCar() global_car:test()
其格式如下:
1
---@type my_type[|other_type] [@comment]
举个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13
---@type Car @instance of car local car1 = {}
---@type Car|Ship @transport tools, car or ship. Since lua is dynamic-typed, a variable may be of different types ---use | to list all possible types local transport = {}
---@type Car @global variable type global_car = {}
local obj = {} ---@type Car @property type obj.car = getCar()
别名注释
使用@alias将一些复杂不容易输入的类型注册为新的容易输入的类型 其格式如下:
1
---@alias new_name type
举个例子:
1 2 3 4
---@alias Handler fun( type: string, data: any):void ---@param handler Handler function addHandler(handler) end
---@vararg string ---@return string local function format(...) local tbl = {...} --inferred as string[] end
嵌入其他语言
使用@language可以在lua代码中嵌入其他语言 其格式如下:
1
---@language language_id
举个例子:
1 2 3 4
---@language JSON local jsonText = [[{ "name":"Emmy" }]]
数组类型声明
使用@type mytype[]可以指定变量类型为数组 其格式如下:
1
---@type my_type[]
举个例子:
1 2 3 4 5 6 7 8
---@type Car[] local list = {} local car = list[1] -- car, and you 'll see completion
for i, car in pairs(list) do -- car. and you'll see completion end
table类型声明
使用@type table可以表示某变量为表格类型 其格式如下:
1
---@type table<key_type, value_type>
举个例子:
1 2 3 4 5 6 7
---@type table<string, Car> local dict = {} local car = dict['key'] -- car. and you'll see completion for key, car in pairs(dict) do -- car. and you'll see completion end
函数声明
使用fun(param:my_type):return_type来表示函数类型变量 其格式如下:
1
---@type fun(param:my_type):return_type
举个例子:
1 2 3 4 5 6 7 8 9 10 11 12
@type fun(key:string):Car local carCreatorFn1
local car = carCreatorFn1('key') -- car. and you see code completion
---@type fun():Car[] local carCreatorFn2
for i, car in pairs(carCreatorFn2()) do -- car. and you see completion end