refactor(class): type checking

This commit is contained in:
Linden
2023-12-18 11:17:48 +11:00
parent 955acabd3c
commit 8a5232c056

View File

@@ -9,8 +9,22 @@ local private_mt = {
__pack = function() return '' end, __pack = function() return '' end,
} }
---@param id number | string
---@param var any
---@param expected type
local function assertType(id, var, expected)
local received = type(var)
if received ~= expected then
error(("expected %s %s to have type '%s' (received %s)"):format(type(id) == 'string' and 'field' or 'argument', id, expected, received), 3)
end
return true
end
local function newClass(self, obj) local function newClass(self, obj)
if obj.private then if obj.private then
assertType('private', obj.private, 'table')
setmetatable(obj.private, private_mt) setmetatable(obj.private, private_mt)
end end
@@ -33,8 +47,10 @@ local function setMetamethod(self, metamethod, value)
rawset(getmetatable(self), metamethod, value) rawset(getmetatable(self), metamethod, value)
end end
---@param name? string ---@param name string
function lib.class.new(name) function lib.class.new(name)
assertType(1, name, 'string')
local data = {} local data = {}
local class = { local class = {
__index = data, __index = data,