• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

TradeSkillMaster / LibTSMClass / 26375476069

24 May 2026 11:14PM UTC coverage: 95.437% (-0.4%) from 95.808%
26375476069

push

github

web-flow
Alias :ToDebugString() to __tostring() (#37)

1 of 3 new or added lines in 1 file covered. (33.33%)

481 of 504 relevant lines covered (95.44%)

27.01 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.44
/LibTSMClass.lua
1
--- LibTSMClass Library
2
-- Allows for OOP in lua through the implementation of classes. Many features of proper classes are supported including
3
-- inhertiance, polymorphism, and virtual methods.
4
-- @author TradeSkillMaster Team (admin@tradeskillmaster.com)
5
-- @license MIT
6

7
local MINOR_REVISION = 2
1✔
8
local Lib = {} ---@class LibTSMClass
1✔
9
local private = {
1✔
10
        classInfo = {},
1✔
11
        extensionInfo = {},
1✔
12
        instInfo = {},
1✔
13
        constructTbl = nil,
1✔
14
        tempTable = {},
1✔
15
}
16
-- Set the keys as weak so that class extensions and instances of classes can be GC'd (classes are never GC'd)
17
local WEAK_KEY_MT = { __mode = "k" }
1✔
18
setmetatable(private.extensionInfo, WEAK_KEY_MT)
1✔
19
setmetatable(private.instInfo, WEAK_KEY_MT)
1✔
20
local RESERVED_KEYS = {
1✔
21
        __super = true,
1✔
22
        __isa = true,
1✔
23
        __class = true,
1✔
24
        __name = true,
1✔
25
        __as = true,
1✔
26
        __static = true,
1✔
27
        __private = true,
1✔
28
        __protected = true,
1✔
29
        __abstract = true,
1✔
30
        __closure = true,
1✔
31
        __extend = true,
1✔
32
}
33
local DEFAULT_INST_FIELDS = {
1✔
34
        __init = function(self)
35
                -- Do nothing
36
        end,
37
        __tostring = function(self)
38
                return private.instInfo[self].str
1✔
39
        end,
40
        ToDebugString = function(self)
NEW
41
                return private.instInfo[self].str
×
42
        end,
43
        __equals = function(self, other)
44
                return rawequal(self, other)
×
45
        end,
46
        __dump = function(self)
47
                private.InstDump(self)
1✔
48
        end,
49
}
50
local DUMP_KEY_PATH_DELIM = "\001"
1✔
51

52

53

54
-- ============================================================================
55
-- Public Library Functions
56
-- ============================================================================
57

58
---@class Class<S>
59
---@overload fun(): Class
60
---@constructor __init
61
---@field __class Class
62
---@field __name string
63
---@field __super S
64
---@field __isa fun(self, class: Class): boolean
65
---@field protected __closure fun(self, name: string): function
66
---@field __tostring fun(self): string
67
---@field __equals fun(self, other: any): boolean
68
---@field __dump fun(self)
69
---@accessor __private private
70
---@accessor __protected protected
71
---@accessor __abstract protected
72
---@accessor __static
73

74
---@alias ClassProperties
75
---|'"ABSTRACT"' # An abstract class cannot be directly instantiated
76

77
---Defines a new class.
78
---@defclass T : P
79
---@generic T: Class<P>
80
---@generic P: Class
81
---@param name `T` The name of the class
82
---@param superclass? P The superclass
83
---@param ... ClassProperties Properties to define the class with
84
---@return T
85
function Lib.DefineClass(name, superclass, ...)
1✔
86
        if type(name) ~= "string" then
37✔
87
                error("Invalid class name: "..tostring(name), 2)
1✔
88
        end
89
        if superclass ~= nil and (type(superclass) ~= "table" or not private.classInfo[superclass]) then
36✔
90
                error("Invalid superclass: "..tostring(superclass), 2)
1✔
91
        end
92
        local abstract = false
35✔
93
        for i = 1, select('#', ...) do
39✔
94
                local modifier = select(i, ...)
5✔
95
                if modifier == "ABSTRACT" then
5✔
96
                        abstract = true
4✔
97
                else
98
                        error("Invalid modifier: "..tostring(modifier), 2)
1✔
99
                end
100
        end
101

102
        local class = setmetatable({}, private.CLASS_MT)
34✔
103
        private.classInfo[class] = {
34✔
104
                name = name,
34✔
105
                static = {},
34✔
106
                superStatic = {},
34✔
107
                superclass = superclass,
34✔
108
                abstract = abstract,
34✔
109
                referenceType = nil,
34✔
110
                subclassed = false,
34✔
111
                extended = false,
34✔
112
                methodProperties = nil, -- Set as needed
34✔
113
                inClassFunc = 0,
34✔
114
                instances = setmetatable({}, WEAK_KEY_MT),
34✔
115
        }
34✔
116
        while superclass do
56✔
117
                local superclassInfo = private.classInfo[superclass]
22✔
118
                for key, value in pairs(superclassInfo.static) do
95✔
119
                        if not private.classInfo[class].superStatic[key] then
73✔
120
                                private.classInfo[class].superStatic[key] = {
67✔
121
                                        class = superclass,
67✔
122
                                        value = value,
67✔
123
                                        properties = superclassInfo.methodProperties and superclassInfo.methodProperties[key] or nil,
67✔
124
                                }
67✔
125
                        end
126
                end
127
                if superclassInfo.extended then
22✔
128
                        error("Cannot subclass a class after it's extended", 2)
×
129
                end
130
                superclassInfo.subclassed = true
22✔
131
                superclass = superclass.__super
22✔
132
        end
133
        return class
34✔
134
end
135

136
---Constructs a class from an existing table, preserving its keys.
137
---@generic T
138
---@param tbl table The table with existing keys to preserve
139
---@param class T The class to construct
140
---@param ... any Arguments to pass to the constructor
141
---@return T
142
function Lib.ConstructWithTable(tbl, class, ...)
1✔
143
        private.constructTbl = tbl
1✔
144
        local inst = class(...)
1✔
145
        assert(not private.constructTbl and inst == tbl, "Internal error")
1✔
146
        return inst
1✔
147
end
148

149
---Gets instance properties from an instance string for debugging purposes.
150
---@param instStr string The string representation of the instance
151
---@param maxDepth number The maximum depth to recurse into tables
152
---@param tableLookupFunc? fun(tbl: table): string? A lookup function which is used to get debug information for an unknown table
153
---@return string? @The properties dumped as a multiline string
154
function Lib.GetDebugInfo(instStr, maxDepth, tableLookupFunc)
1✔
155
        local inst = nil
156
        for obj, info in pairs(private.instInfo) do
5✔
157
                if info.str == instStr then
4✔
158
                        inst = obj
1✔
159
                        break
1✔
160
                end
161
        end
162
        if not inst then
2✔
163
                return nil
1✔
164
        end
165
        assert(not next(private.tempTable))
1✔
166
        private.InstDump(inst, private.tempTable, maxDepth, tableLookupFunc)
1✔
167
        local result = table.concat(private.tempTable, "\n")
1✔
168
        wipe(private.tempTable)
1✔
169
        return result
1✔
170
end
171

172

173

174
-- ============================================================================
175
-- Instance Metatable
176
-- ============================================================================
177

178
private.INST_MT = {
1✔
179
        __newindex = function(self, key, value)
180
                if RESERVED_KEYS[key] then
50✔
181
                        error("Can't set reserved key: "..tostring(key), 2)
1✔
182
                end
183
                if private.classInfo[self.__class].static[key] ~= nil then
49✔
184
                        private.classInfo[self.__class].static[key] = value
2✔
185
                elseif not private.instInfo[self].hasSuperclass then
47✔
186
                        -- We just set this directly on the instance table for better performance
187
                        rawset(self, key, value)
20✔
188
                else
189
                        private.instInfo[self].fields[key] = value
27✔
190
                end
191
        end,
192
        __index = function(self, key)
193
                -- This method is super optimized since it's used for every class instance access, meaning function calls and
194
                -- table lookup is kept to an absolute minimum, at the expense of readability and code reuse.
195
                local instInfo = private.instInfo[self]
272✔
196

197
                -- Check if this key is an instance field first, since this is the most common case
198
                local res = instInfo.fields[key]
272✔
199
                if res ~= nil then
272✔
200
                        instInfo.currentClass = nil
84✔
201
                        return res
84✔
202
                end
203

204
                -- Check if it's a special field / method
205
                if key == "__super" then
188✔
206
                        if not instInfo.hasSuperclass then
29✔
207
                                error("The class of this instance has no superclass", 2)
2✔
208
                        end
209
                        -- The class of the current class method we are in, or nil if we're not in a class method.
210
                        local methodClass = instInfo.methodClass
27✔
211
                        -- We can only access the superclass within a class method and will use the class which defined that method
212
                        -- as the base class to jump to the superclass of, regardless of what class the instance actually is.
213
                        if not methodClass then
27✔
214
                                error("The superclass can only be referenced within a class method", 2)
1✔
215
                        end
216
                        return private.InstAs(self, private.classInfo[instInfo.currentClass or methodClass].superclass)
26✔
217
                elseif key == "__as" then
159✔
218
                        return private.InstAs
17✔
219
                elseif key == "__closure" then
142✔
220
                        return private.InstClosure
11✔
221
                end
222

223
                -- Reset the current class since we're not continuing the __super chain
224
                local class = instInfo.currentClass or instInfo.class
131✔
225
                instInfo.currentClass = nil
131✔
226

227
                -- Check if this is a static key
228
                local classInfo = private.classInfo[class]
131✔
229
                res = classInfo.static[key]
131✔
230
                if res ~= nil then
131✔
231
                        return res
72✔
232
                end
233

234
                -- Check if it's a static field in the superclass
235
                local superStaticRes = classInfo.superStatic[key]
59✔
236
                if superStaticRes then
59✔
237
                        res = superStaticRes.value
39✔
238
                        return res
39✔
239
                end
240

241
                -- Check if this field has a default value
242
                res = DEFAULT_INST_FIELDS[key]
20✔
243
                if res ~= nil then
20✔
244
                        return res
15✔
245
                end
246

247
                return nil
5✔
248
        end,
249
        __eq = function(self, other)
250
                if self.__class ~= other.__class then
5✔
251
                        return false
2✔
252
                end
253
                return self:__equals(other)
3✔
254
        end,
255
        __tostring = function(self)
256
                return self:__tostring()
4✔
257
        end,
258
        __metatable = false,
1✔
259
}
1✔
260

261

262

263
-- ============================================================================
264
-- Class Metatable
265
-- ============================================================================
266

267
private.CLASS_MT = {
1✔
268
        __newindex = function(self, key, value)
269
                if type(key) ~= "string" then
106✔
270
                        error("Can't index class with non-string key", 2)
1✔
271
                end
272
                local classInfo = private.classInfo[self]
105✔
273
                if classInfo.subclassed or classInfo.extended then
105✔
274
                        error("Can't modify classes after they are subclassed or extended", 2)
1✔
275
                end
276
                if classInfo.static[key] ~= nil then
104✔
277
                        error("Can't modify or override static members", 2)
1✔
278
                end
279
                if RESERVED_KEYS[key] then
103✔
280
                        error("Reserved word: "..key, 2)
1✔
281
                end
282
                local isFunction = type(value) == "function"
102✔
283
                local methodProperty = classInfo.referenceType
102✔
284
                local isStatic = methodProperty == "STATIC"
102✔
285
                classInfo.referenceType = nil
102✔
286
                if isFunction and isStatic then
102✔
287
                        -- We are defining a static class function
288
                        classInfo.methodProperties = classInfo.methodProperties or {}
8✔
289
                        classInfo.methodProperties[key] = "STATIC"
8✔
290
                        -- We wrap static methods so that we can allow private or protected access within them
291
                        classInfo.static[key] = function(...)
8✔
292
                                local tempMethodClassInfo = classInfo
8✔
293
                                while tempMethodClassInfo do
20✔
294
                                        tempMethodClassInfo.inClassFunc = tempMethodClassInfo.inClassFunc + 1
12✔
295
                                        local superclass = tempMethodClassInfo.superclass
12✔
296
                                        tempMethodClassInfo = superclass and private.classInfo[superclass] or nil
12✔
297
                                end
298
                                return private.StaticFuncReturnHelper(classInfo, value(...))
8✔
299
                        end
300
                elseif isFunction and not isStatic then
94✔
301
                        -- We are defining a class method
302
                        local superclass = classInfo.superclass
89✔
303
                        while superclass do
121✔
304
                                local superclassInfo = private.classInfo[superclass]
57✔
305
                                local superclassMethodProperty = superclassInfo.methodProperties and superclassInfo.methodProperties[key] or nil
57✔
306
                                if superclassInfo.static[key] ~= nil or superclassMethodProperty ~= nil then
57✔
307
                                        if superclassInfo.static[key] ~= nil and type(superclassInfo.static[key]) ~= "function" then
25✔
308
                                                error(format("Attempting to override non-method superclass property (%s) with method", key), 2)
1✔
309
                                        end
310
                                        if superclassMethodProperty == nil then
24✔
311
                                                -- Can only override public methods with public methods
312
                                                if methodProperty ~= nil then
11✔
313
                                                        error(format("Overriding a public superclass method (%s) can only be done with a public method", key), 2)
1✔
314
                                                end
315
                                        elseif superclassMethodProperty == "ABSTRACT" then
13✔
316
                                                -- Can only override abstract methods with protected methods
317
                                                if methodProperty ~= "PROTECTED" then
5✔
318
                                                        error(format("Overriding an abstract superclass method (%s) can only be done with a protected method", key), 2)
1✔
319
                                                end
320
                                        elseif superclassMethodProperty == "PROTECTED" then
8✔
321
                                                -- Can only override protected methods with protected methods
322
                                                if methodProperty ~= "PROTECTED" then
5✔
323
                                                        error(format("Overriding a protected superclass method (%s) can only be done with a protected method", key), 2)
2✔
324
                                                end
325
                                        elseif superclassMethodProperty == "STATIC" then
3✔
326
                                                -- Can't override static properties with methods
327
                                                error(format("Can't override static superclass property (%s) with method", key), 2)
1✔
328
                                        elseif superclassMethodProperty == "PRIVATE" then
2✔
329
                                                -- Can't override private methods
330
                                                error(format("Can't override private superclass method (%s)", key), 2)
2✔
331
                                        else
332
                                                -- luacov: disable
333
                                                -- Should never get here
334
                                                error("Unexpected superclassMethodProperty: "..tostring(superclassMethodProperty))
335
                                                -- luacov: enable
336
                                        end
337
                                        -- Just need to go up the superclass tree until we find the first one which references this key
338
                                        break
339
                                end
340
                                superclass = superclassInfo.superclass
32✔
341
                        end
342
                        local isPrivate, isProtected = false, false
81✔
343
                        if methodProperty ~= nil then
81✔
344
                                classInfo.methodProperties = classInfo.methodProperties or {}
23✔
345
                                classInfo.methodProperties[key] = methodProperty
23✔
346
                                if methodProperty == "PRIVATE" then
23✔
347
                                        isPrivate = true
8✔
348
                                elseif methodProperty == "PROTECTED" then
15✔
349
                                        isProtected = true
12✔
350
                                elseif methodProperty == "ABSTRACT" then
3✔
351
                                        -- Just need to set the property
352
                                        return
3✔
353
                                else
354
                                        -- luacov: disable
355
                                        -- Should never get here
356
                                        error("Unknown method property: "..tostring(methodProperty))
357
                                        -- luacov: enable
358
                                end
359
                        end
360
                        -- We wrap class methods so that within them, the instance appears to be of the defining class
361
                        classInfo.static[key] = function(inst, ...)
78✔
362
                                local instInfo = private.instInfo[inst]
150✔
363
                                if not instInfo or not instInfo.isClassLookup[self] then
150✔
364
                                        error(format("Attempt to call class method on non-object (%s)", tostring(inst)), 2)
1✔
365
                                end
366
                                local prevMethodClass = instInfo.methodClass
149✔
367
                                if isPrivate and prevMethodClass ~= self and (prevMethodClass ~= nil or classInfo.inClassFunc == 0) then
149✔
368
                                        error(format("Attempting to call private method (%s) from outside of class", key), 2)
6✔
369
                                end
370
                                if isProtected and prevMethodClass == nil and classInfo.inClassFunc == 0 then
143✔
371
                                        -- Check if we're in a super class func
372
                                        error(format("Attempting to call protected method (%s) from outside of class", key), 2)
5✔
373
                                end
374
                                instInfo.methodClass = self
138✔
375
                                local tempMethodClassInfo = classInfo
138✔
376
                                while tempMethodClassInfo do
357✔
377
                                        tempMethodClassInfo.inClassFunc = tempMethodClassInfo.inClassFunc + 1
219✔
378
                                        local tempSuperclass = tempMethodClassInfo.superclass
219✔
379
                                        tempMethodClassInfo = tempSuperclass and private.classInfo[tempSuperclass] or nil
219✔
380
                                end
381
                                return private.InstMethodReturnHelper(prevMethodClass, instInfo, classInfo, value(inst, ...))
138✔
382
                        end
383
                elseif not isFunction then
5✔
384
                        -- We are defining a static property (shouldn't be explicitly marked as static)
385
                        if isStatic then
5✔
386
                                error("Unnecessary __static for non-function class property", 2)
1✔
387
                        end
388
                        classInfo.static[key] = value
4✔
389
                end
390
        end,
391
        __index = function(self, key)
392
                local classInfo = private.classInfo[self]
74✔
393
                if classInfo.referenceType ~= nil then
74✔
394
                        error("Can't index into property table", 2)
1✔
395
                end
396
                if key == "__isa" then
73✔
397
                        return private.ClassIsA
3✔
398
                elseif key == "__name" then
70✔
399
                        return classInfo.name
1✔
400
                elseif key == "__super" then
69✔
401
                        return classInfo.superclass
23✔
402
                elseif key == "__static" then
46✔
403
                        classInfo.referenceType = "STATIC"
9✔
404
                        return self
9✔
405
                elseif key == "__private" then
37✔
406
                        classInfo.referenceType = "PRIVATE"
9✔
407
                        return self
9✔
408
                elseif key == "__protected" then
28✔
409
                        classInfo.referenceType = "PROTECTED"
13✔
410
                        return self
13✔
411
                elseif key == "__abstract" then
15✔
412
                        if not classInfo.abstract then
4✔
413
                                error("Can only define abstract methods on abstract classes", 2)
1✔
414
                        end
415
                        classInfo.referenceType = "ABSTRACT"
3✔
416
                        return self
3✔
417
                elseif key == "__extend" then
11✔
418
                        return private.ClassExtend
1✔
419
                elseif classInfo.static[key] ~= nil then
10✔
420
                        return classInfo.static[key]
8✔
421
                elseif classInfo.superStatic[key] then
2✔
422
                        return classInfo.superStatic[key].value
1✔
423
                elseif key == "ToDebugString" then
1✔
NEW
424
                        return private.CLASS_MT.__tostring
×
425
                end
426
                error(format("Invalid static class key (%s)", tostring(key)), 2)
1✔
427
        end,
428
        __tostring = function(self)
429
                return "class:"..private.classInfo[self].name
11✔
430
        end,
431
        __call = function(self, ...)
432
                if private.classInfo[self].abstract then
42✔
433
                        error("Attempting to instantiate an abstract class", 2)
1✔
434
                end
435
                -- Create a new instance of this class
436
                local inst = private.constructTbl or {}
41✔
437
                local instStr = strmatch(tostring(inst), "table:[^1-9a-fA-F]*([0-9a-fA-F]+)")
41✔
438
                setmetatable(inst, private.INST_MT)
41✔
439
                local classInfo = private.classInfo[self]
41✔
440
                local hasSuperclass = classInfo.superclass and true or false
41✔
441
                private.instInfo[inst] = {
41✔
442
                        class = self,
41✔
443
                        fields = {
41✔
444
                                __class = self,
41✔
445
                                __isa = private.InstIsA,
41✔
446
                        },
41✔
447
                        str = classInfo.name..":"..instStr,
41✔
448
                        isClassLookup = {},
41✔
449
                        hasSuperclass = hasSuperclass,
41✔
450
                        currentClass = nil,
41✔
451
                        closures = {},
41✔
452
                }
41✔
453
                classInfo.instances[inst] = true
41✔
454
                if not hasSuperclass then
41✔
455
                        -- Set the static members directly on this object for better performance
456
                        for key, value in pairs(classInfo.static) do
65✔
457
                                rawset(inst, key, value)
46✔
458
                        end
459
                end
460
                -- Check that all the abstract methods have been defined
461
                assert(not next(private.tempTable))
41✔
462
                local c = self
41✔
463
                while c do
110✔
464
                        private.instInfo[inst].isClassLookup[c] = true
69✔
465
                        c = private.classInfo[c].superclass
69✔
466
                        if c and private.classInfo[c] and private.classInfo[c].methodProperties then
69✔
467
                                for methodName, property in pairs(private.classInfo[c].methodProperties) do
61✔
468
                                        if property == "ABSTRACT" then
40✔
469
                                                private.tempTable[methodName] = true
9✔
470
                                        end
471
                                end
472
                        end
473
                end
474
                for methodName in pairs(private.tempTable) do
48✔
475
                        if type(classInfo.static[methodName]) ~= "function" then
9✔
476
                                -- Check the superclasses
477
                                local found = false
4✔
478
                                local c2 = self
4✔
479
                                while c2 and not found do
11✔
480
                                        c2 = private.classInfo[c2].superclass
7✔
481
                                        if c2 and private.classInfo[c2] and private.classInfo[c2].static[methodName] then
7✔
482
                                                found = true
2✔
483
                                        end
484
                                end
485
                                if not found then
4✔
486
                                        wipe(private.tempTable)
2✔
487
                                        error("Missing abstract method: "..tostring(methodName), 2)
2✔
488
                                end
489
                        end
490
                end
491
                wipe(private.tempTable)
39✔
492
                if private.constructTbl then
39✔
493
                        -- Re-set all the object attributes through the proper metamethod
494
                        assert(not next(private.tempTable))
1✔
495
                        for k, v in pairs(inst) do
5✔
496
                                private.tempTable[k] = v
4✔
497
                        end
498
                        for k, v in pairs(private.tempTable) do
5✔
499
                                rawset(inst, k, nil)
4✔
500
                                inst[k] = v
4✔
501
                        end
502
                        wipe(private.tempTable)
1✔
503
                        private.constructTbl = nil
1✔
504
                end
505
                if select("#", inst:__init(...)) > 0 then
39✔
506
                        error("__init(...) must not return any values", 2)
1✔
507
                end
508
                return inst
34✔
509
        end,
510
        __metatable = false,
1✔
511
}
1✔
512

513

514

515
-- ============================================================================
516
-- Extension Metatable
517
-- ============================================================================
518

519
private.EXTENSION_MT = {
1✔
520
        __newindex = function(self, key, value)
521
                if type(key) ~= "string" then
2✔
522
                        error("Can't index class extension with non-string key", 2)
×
523
                elseif type(value) ~= "function" then
2✔
524
                        error("Can only add class methods via class extension", 2)
×
525
                elseif RESERVED_KEYS[key] then
2✔
526
                        error("Reserved word: "..key, 2)
×
527
                end
528
                local class = private.extensionInfo[self].class
2✔
529
                local classInfo = private.classInfo[class]
2✔
530
                if classInfo.subclassed then
2✔
531
                        error("Can't add extension methods after a class is subclassed", 2)
×
532
                end
533
                local testClass = class
2✔
534
                while testClass do
4✔
535
                        local testClassInfo = private.classInfo[testClass]
2✔
536
                        if testClassInfo.static[key] ~= nil then
2✔
537
                                error("Can't modify or override class members from extension", 2)
×
538
                        end
539
                        testClass = testClassInfo.superclass
2✔
540
                end
541
                -- Don't need to wrap extension methods because they are treated as if they are outside
542
                -- the class as far as access restrictions are concerned and don't need to worry about
543
                -- virtual methods since extensions only support non-subclassed classes.
544
                classInfo.static[key] = value
2✔
545
                -- Add the new method directly to all previously-created instances
546
                for inst in pairs(classInfo.instances) do
5✔
547
                        rawset(inst, key, value)
3✔
548
                end
549
        end,
550
        __index = function()
551
                error("Extension objects are write-only", 2)
×
552
        end,
553
        __tostring = function(self)
554
                return "classExtension:"..private.classInfo[private.extensionInfo[self].class].name
×
555
        end,
556
        __metatable = false,
1✔
557
}
1✔
558

559

560

561
-- ============================================================================
562
-- Helper Functions
563
-- ============================================================================
564

565
function private.ClassIsA(class, targetClass)
1✔
566
        while class do
4✔
567
                if class == targetClass then return true end
4✔
568
                class = class.__super
1✔
569
        end
570
end
571

572
function private.ClassExtend(class)
1✔
573
        local classInfo = private.classInfo[class]
1✔
574
        if not classInfo then
1✔
575
                error("__extend() must be called with `:` to pass the class", 2)
×
576
        elseif classInfo.subclassed then
1✔
577
                error("Can't add extension methods after a class is subclassed", 2)
×
578
        end
579
        classInfo.extended = true
1✔
580
        local extensionObj = setmetatable({}, private.EXTENSION_MT)
1✔
581
        private.extensionInfo[extensionObj] = {
1✔
582
                class = class,
1✔
583
        }
1✔
584
        return extensionObj
1✔
585
end
586

587
function private.InstMethodReturnHelper(class, instInfo, classInfo, ...)
1✔
588
        -- Reset methodClass and decrement inClassFunc now that the function returned
589
        instInfo.methodClass = class
122✔
590
        while classInfo do
319✔
591
                classInfo.inClassFunc = classInfo.inClassFunc - 1
197✔
592
                local superclass = classInfo.superclass
197✔
593
                classInfo = superclass and private.classInfo[superclass] or nil
197✔
594
        end
595
        return ...
122✔
596
end
597

598
function private.StaticFuncReturnHelper(classInfo, ...)
1✔
599
        -- Decrement inClassFunc now that the function returned
600
        while classInfo do
20✔
601
                classInfo.inClassFunc = classInfo.inClassFunc - 1
12✔
602
                local superclass = classInfo.superclass
12✔
603
                classInfo = superclass and private.classInfo[superclass] or nil
12✔
604
        end
605
        return ...
8✔
606
end
607

608
function private.InstIsA(inst, targetClass)
1✔
609
        return private.instInfo[inst].isClassLookup[targetClass]
2✔
610
end
611

612
function private.InstAs(inst, targetClass)
1✔
613
        local instInfo = private.instInfo[inst]
43✔
614
        -- Clear currentClass while we perform our checks so we can better recover from errors
615
        instInfo.currentClass = nil
43✔
616
        if not targetClass then
43✔
617
                error(format("Requested class does not exist"), 2)
4✔
618
        elseif not instInfo.isClassLookup[targetClass] then
39✔
619
                error(format("Object is not an instance of the requested class (%s)", tostring(targetClass)), 2)
3✔
620
        end
621
        -- For classes with no superclass, we don't go through the __index metamethod, so can't use __as
622
        if not instInfo.hasSuperclass then
36✔
623
                error("The class of this instance has no superclass", 2)
1✔
624
        end
625
        -- We can only access the superclass within a class method.
626
        if not instInfo.methodClass then
35✔
627
                error("The superclass can only be referenced within a class method", 2)
1✔
628
        end
629
        instInfo.currentClass = targetClass
34✔
630
        return inst
34✔
631
end
632

633
function private.InstClosure(inst, methodName)
1✔
634
        local instInfo = private.instInfo[inst]
11✔
635
        local methodClass = instInfo.methodClass
11✔
636
        if not methodClass then
11✔
637
                error("Closures can only be created within a class method", 2)
1✔
638
        elseif instInfo.currentClass then
10✔
639
                error("Cannot create closure as superclass", 2)
1✔
640
        end
641
        -- Check for this method on the class
642
        local classInfo = private.classInfo[instInfo.class]
9✔
643
        local methodFunc = classInfo.static[methodName]
9✔
644
        if methodFunc then
9✔
645
                -- If this method is private, make sure we're within the class
646
                if classInfo.methodProperties and classInfo.methodProperties[methodName] == "PRIVATE" and instInfo.class ~= methodClass then
5✔
647
                        error("Attempt to create closure for private virtual method", 2)
1✔
648
                end
649
        else
650
                -- Check for this method on the superclass
651
                local superInfo = classInfo.superStatic[methodName]
4✔
652
                if superInfo then
4✔
653
                        if superInfo.properties == "PRIVATE" and not private.classInfo[methodClass].static[methodName] then
3✔
654
                                error("Attempt to create closure for private superclass method", 2)
1✔
655
                        end
656
                        methodFunc = superInfo.value
2✔
657
                end
658
        end
659
        if type(methodFunc) ~= "function" then
7✔
660
                error("Attempt to create closure for non-method field", 2)
1✔
661
        end
662
        local methodClassInfo = private.classInfo[methodClass]
6✔
663
        local cacheKey = tostring(methodClass).."."..methodName
6✔
664
        if not instInfo.closures[cacheKey] then
6✔
665
                instInfo.closures[cacheKey] = function(...)
6✔
666
                        if instInfo.methodClass == methodClass then
8✔
667
                                -- We're already within a method of the class, so just call the method normally
668
                                return methodFunc(inst, ...)
5✔
669
                        else
670
                                -- Pretend we are within the class which created the closure
671
                                local prevClass = instInfo.methodClass
3✔
672
                                instInfo.methodClass = methodClass
3✔
673
                                local tempMethodClassInfo = methodClassInfo
3✔
674
                                while tempMethodClassInfo do
9✔
675
                                        tempMethodClassInfo.inClassFunc = tempMethodClassInfo.inClassFunc + 1
6✔
676
                                        local superclass = tempMethodClassInfo.superclass
6✔
677
                                        tempMethodClassInfo = superclass and private.classInfo[superclass] or nil
6✔
678
                                end
679
                                return private.InstMethodReturnHelper(prevClass, instInfo, methodClassInfo, methodFunc(inst, ...))
3✔
680
                        end
681
                end
682
        end
683
        return instInfo.closures[cacheKey]
6✔
684
end
685

686
function private.InstDump(inst, resultTbl, maxDepth, tableLookupFunc)
1✔
687
        local context = {
2✔
688
                resultTbl = resultTbl,
2✔
689
                maxDepth = maxDepth or 2,
2✔
690
                maxTableEntries = 100,
2✔
691
                tableLookupFunc = tableLookupFunc,
2✔
692
                tableRefs = {},
2✔
693
                depth = 0,
2✔
694
        }
695

696
        -- Build up our table references via a breadth-first search
697
        local bfsQueueKeyPath = {""}
2✔
698
        local bfsQueueDepth = {0}
2✔
699
        local bfsQueueValue = {inst}
2✔
700
        while #bfsQueueKeyPath > 0 do
18✔
701
                local keyPath = tremove(bfsQueueKeyPath, 1)
16✔
702
                local depth = tremove(bfsQueueDepth, 1)
16✔
703
                local value = tremove(bfsQueueValue, 1)
16✔
704
                if not context.tableRefs[value] then
16✔
705
                        context.tableRefs[value] = keyPath
14✔
706
                        if depth <= context.maxDepth and not private.classInfo[value] then
14✔
707
                                if private.instInfo[value] then
10✔
708
                                        local instInfo = private.instInfo[value]
2✔
709
                                        value = instInfo.hasSuperclass and instInfo.fields or value
2✔
710
                                end
711
                                for k, v in pairs(value) do
38✔
712
                                        if type(v) == "table" and (type(k) == "string" or type(k) == "number") and not strfind(k, DUMP_KEY_PATH_DELIM, nil, true) then
28✔
713
                                                tinsert(bfsQueueKeyPath, keyPath..DUMP_KEY_PATH_DELIM..k)
14✔
714
                                                tinsert(bfsQueueDepth, depth + 1)
14✔
715
                                                tinsert(bfsQueueValue, v)
14✔
716
                                        end
717
                                end
718
                        end
719
                end
720
        end
721

722
        private.InstDumpVariable("self", inst, context, "")
2✔
723
end
724

725
function private.InstDumpVariable(key, value, context, strKeyPath)
1✔
726
        if strfind(key, DUMP_KEY_PATH_DELIM, nil, true) then
30✔
727
                -- Ignore keys with our deliminator in them
728
                return
×
729
        end
730
        if type(value) == "table" and private.classInfo[value] then
30✔
731
                -- This is a class
732
                private.InstDumpKeyValue(key, "\""..tostring(value).."\"", context)
2✔
733
        elseif type(value) == "table" then
28✔
734
                local refKeyPath = context.tableRefs[value]
14✔
735
                if not refKeyPath then
14✔
736
                        return
×
737
                end
738
                if refKeyPath ~= strKeyPath then
14✔
739
                        local refValue = "\"REF{"..gsub(refKeyPath, DUMP_KEY_PATH_DELIM, ".").."}\""
2✔
740
                        private.InstDumpKeyValue(key, refValue, context)
2✔
741
                elseif private.instInfo[value] then
12✔
742
                        -- This is an instance of a class
743
                        if context.depth <= context.maxDepth then
2✔
744
                                -- Recurse into the class
745
                                local instInfo = private.instInfo[value]
2✔
746
                                local tbl = instInfo.hasSuperclass and instInfo.fields or value
2✔
747
                                private.InstDumpLine(key.." = <"..instInfo.str.."> {", context)
2✔
748
                                context.depth = context.depth + 1
2✔
749
                                for key2, value2 in pairs(tbl) do
16✔
750
                                        if type(key2) == "string" or type(key2) == "number" or type(key2) == "boolean" then
14✔
751
                                                key2 = tostring(key2)
14✔
752
                                                private.InstDumpVariable(key2, value2, context, strKeyPath..DUMP_KEY_PATH_DELIM..key2)
14✔
753
                                        end
754
                                end
755
                                context.depth = context.depth - 1
2✔
756
                                private.InstDumpLine("}", context)
2✔
757
                        else
758
                                private.InstDumpKeyValue(key, "\""..tostring(value).."\"", context)
×
759
                        end
760
                else
761
                        local isEmpty = true
10✔
762
                        for _, value2 in pairs(value) do
10✔
763
                                local valueType = type(value2)
8✔
764
                                if valueType == "string" or valueType == "number" or valueType == "boolean" or valueType == "table" then
8✔
765
                                        isEmpty = false
8✔
766
                                        break
8✔
767
                                end
768
                        end
769
                        if isEmpty then
10✔
770
                                local info = context.tableLookupFunc and context.tableLookupFunc(value) or nil
2✔
771
                                if info and context.depth <= context.maxDepth then
2✔
772
                                        -- Display the table values
773
                                        private.InstDumpKeyValue(key, "{", context)
×
774
                                        context.depth = context.depth + 1
×
775
                                        for _, line in ipairs({strsplit("\n", info)}) do
×
776
                                                private.InstDumpLine(line, context)
×
777
                                        end
778
                                        context.depth = context.depth - 1
×
779
                                        private.InstDumpLine("}", context)
×
780
                                elseif info then
2✔
781
                                        private.InstDumpKeyValue(key, "{ ... }", context)
×
782
                                else
783
                                        private.InstDumpKeyValue(key, "{}", context)
2✔
784
                                end
785
                        else
786
                                if context.depth <= context.maxDepth then
8✔
787
                                        -- Recurse into the table
788
                                        private.InstDumpKeyValue(key, "{", context)
6✔
789
                                        context.depth = context.depth + 1
6✔
790
                                        local numTableEntries = 0
6✔
791
                                        for key2, value2 in pairs(value) do
20✔
792
                                                if numTableEntries >= context.maxTableEntries then
14✔
793
                                                        break
794
                                                end
795
                                                if type(key2) == "string" or type(key2) == "number" or type(key2) == "boolean" then
14✔
796
                                                        numTableEntries = numTableEntries + 1
14✔
797
                                                        key2 = tostring(key2)
14✔
798
                                                        private.InstDumpVariable(key2, value2, context, strKeyPath..DUMP_KEY_PATH_DELIM..key2)
14✔
799
                                                end
800
                                        end
801
                                        context.depth = context.depth - 1
6✔
802
                                        private.InstDumpLine("}", context)
6✔
803
                                else
804
                                        private.InstDumpKeyValue(key, "{ ... }", context)
2✔
805
                                end
806
                        end
807
                end
808
        elseif type(value) == "string" then
14✔
809
                private.InstDumpKeyValue(key, "\""..value.."\"", context)
2✔
810
        elseif type(value) == "number" or type(value) == "boolean" then
12✔
811
                private.InstDumpKeyValue(key, value, context)
10✔
812
        end
813
end
814

815
function private.InstDumpLine(line, context)
1✔
816
        line = strrep("  ", context.depth)..line
36✔
817
        if context.resultTbl then
36✔
818
                tinsert(context.resultTbl, line)
18✔
819
        else
820
                print(line)
18✔
821
        end
822
end
823

824
function private.InstDumpKeyValue(key, value, context)
1✔
825
        key = tostring(key)
26✔
826
        if key == "" then
26✔
827
                key = "\"\""
2✔
828
        end
829
        if not context.resultTbl then
26✔
830
                key = "|cff88ccff"..key.."|r"
13✔
831
        end
832
        value = tostring(value)
26✔
833
        local line = format("%s = %s", key, value)
26✔
834
        private.InstDumpLine(line, context)
26✔
835
end
836

837

838

839
-- ============================================================================
840
-- Initialization Code
841
-- ============================================================================
842

843
do
844
        -- Register with LibStub
845
        local libStubTbl = LibStub:NewLibrary("LibTSMClass", MINOR_REVISION)
1✔
846
        if libStubTbl then
1✔
847
                for k, v in pairs(Lib) do
4✔
848
                        libStubTbl[k] = v
3✔
849
                end
850
        end
851
        -- Return the library and our private table for unit testing
852
        return {Lib, private}
1✔
853
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc