refactor(class): improve types

This commit is contained in:
Linden
2024-03-25 20:14:26 +11:00
parent 10db769f41
commit e031f19bea

View File

@@ -21,17 +21,21 @@ local function assertType(id, var, expected)
return true
end
---@alias OxClassConstructor<T> fun(self: T, ...: unknown): nil
---@class OxClass
---@field private __index table
---@field protected __name string
---@field protected private table
---@field protected super function
---@field protected constructor function
---@field protected private? { [string]: unknown }
---@field protected super? OxClassConstructor
---@field protected constructor? OxClassConstructor
local mixins = {}
local constructors = {}
local getinfo = debug.getinfo
---Somewhat hacky way to remove the constructor from the class.__index.
---Maybe add static fields in the future?
---@param class OxClass
local function getConstructor(class)
local constructor = constructors[class] or class.constructor
@@ -47,10 +51,9 @@ local function void() return '' end
---Creates a new instance of the given class.
---@generic T
---@param class T
---@param class T | OxClass
---@return T
function mixins.new(class, ...)
---@cast class +OxClass
local constructor = getConstructor(class)
local obj = {
private = {}
@@ -81,6 +84,7 @@ This behaviour is deprecated and will not be supported in the future.]])
end
constructor(obj, ...)
---@diagnostic disable-next-line: undefined-field
elseif class.init then
lib.print.warn(([[Calling %s:init() is deprecated and will not be supported in the future.
Use %s:constructor(...args) and assign properties in the constructor.]])
@@ -119,22 +123,19 @@ Use %s:constructor(...args) and assign properties in the constructor.]])
obj.private = nil
end
---@cast class -OxClass
return obj
end
---Checks if an object is an instance of the given class.
---@param obj table
---@param class OxClass
function mixins.isClass(obj, class)
return getmetatable(obj) == class
function mixins:isClass(class)
return getmetatable(self) == class
end
---Checks if an object is an instance or derivative of the given class.
---@param obj table
---@param class OxClass
function mixins.instanceOf(obj, class)
local mt = getmetatable(obj)
function mixins:instanceOf(class)
local mt = getmetatable(self)
while mt do
if mt == class then return true end
@@ -155,7 +156,6 @@ function lib.class(name, super)
local class = table.clone(mixins)
class.__name = name
---@diagnostic disable-next-line: inject-field
class.__index = class
if super then