Skip to content

Commit

Permalink
refactor(class): improve types
Browse files Browse the repository at this point in the history
  • Loading branch information
thelindat committed Mar 25, 2024
1 parent 10db769 commit e031f19
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions imports/class/shared.lua
Expand Up @@ -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

Expand All @@ -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 = {}
Expand Down Expand Up @@ -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.]])
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit e031f19

Please sign in to comment.