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

TradeSkillMaster / LibTSMClass / 20490670944

24 Dec 2025 05:06PM UTC coverage: 95.792% (-0.2%) from 96.0%
20490670944

push

github

web-flow
Add __equals() method (#31)

4 of 5 new or added lines in 1 file covered. (80.0%)

478 of 499 relevant lines covered (95.79%)

27.22 hits per line

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

95.79
/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
        __equals = function(self, other)
NEW
41
                return rawequal(self, other)
×
42
        end,
43
        __dump = function(self)
44
                private.InstDump(self)
1✔
45
        end,
46
}
47
local DUMP_KEY_PATH_DELIM = "\001"
1✔
48

49

50

51
-- ============================================================================
52
-- Public Library Functions
53
-- ============================================================================
54

55
---@class Class
56

57
---@alias ClassProperties
58
---|'"ABSTRACT"' # An abstract class cannot be directly instantiated
59

60
---Defines a new class.
61
---@generic T: Class
62
---@param name `T` The name of the class
63
---@param superclass? any The superclass
64
---@param ... ClassProperties Properties to define the class with
65
---@return T
66
function Lib.DefineClass(name, superclass, ...)
1✔
67
        if type(name) ~= "string" then
37✔
68
                error("Invalid class name: "..tostring(name), 2)
1✔
69
        end
70
        if superclass ~= nil and (type(superclass) ~= "table" or not private.classInfo[superclass]) then
36✔
71
                error("Invalid superclass: "..tostring(superclass), 2)
1✔
72
        end
73
        local abstract = false
35✔
74
        for i = 1, select('#', ...) do
39✔
75
                local modifier = select(i, ...)
5✔
76
                if modifier == "ABSTRACT" then
5✔
77
                        abstract = true
4✔
78
                else
79
                        error("Invalid modifier: "..tostring(modifier), 2)
1✔
80
                end
81
        end
82

83
        local class = setmetatable({}, private.CLASS_MT)
34✔
84
        private.classInfo[class] = {
34✔
85
                name = name,
34✔
86
                static = {},
34✔
87
                superStatic = {},
34✔
88
                superclass = superclass,
34✔
89
                abstract = abstract,
34✔
90
                referenceType = nil,
34✔
91
                subclassed = false,
34✔
92
                extended = false,
34✔
93
                methodProperties = nil, -- Set as needed
34✔
94
                inClassFunc = 0,
34✔
95
                instances = setmetatable({}, WEAK_KEY_MT),
34✔
96
        }
34✔
97
        while superclass do
56✔
98
                local superclassInfo = private.classInfo[superclass]
22✔
99
                for key, value in pairs(superclassInfo.static) do
95✔
100
                        if not private.classInfo[class].superStatic[key] then
73✔
101
                                private.classInfo[class].superStatic[key] = {
67✔
102
                                        class = superclass,
67✔
103
                                        value = value,
67✔
104
                                        properties = superclassInfo.methodProperties and superclassInfo.methodProperties[key] or nil,
67✔
105
                                }
67✔
106
                        end
107
                end
108
                if superclassInfo.extended then
22✔
109
                        error("Cannot subclass a class after it's extended", 2)
×
110
                end
111
                superclassInfo.subclassed = true
22✔
112
                superclass = superclass.__super
22✔
113
        end
114
        return class
34✔
115
end
116

117
---Constructs a class from an existing table, preserving its keys.
118
---@generic T
119
---@param tbl table The table with existing keys to preserve
120
---@param class T The class to construct
121
---@param ... any Arguments to pass to the constructor
122
---@return T
123
function Lib.ConstructWithTable(tbl, class, ...)
1✔
124
        private.constructTbl = tbl
1✔
125
        local inst = class(...)
1✔
126
        assert(not private.constructTbl and inst == tbl, "Internal error")
1✔
127
        return inst
1✔
128
end
129

130
---Gets instance properties from an instance string for debugging purposes.
131
---@param instStr string The string representation of the instance
132
---@param maxDepth number The maximum depth to recurse into tables
133
---@param tableLookupFunc? fun(tbl: table): string? A lookup function which is used to get debug information for an unknown table
134
---@return string? @The properties dumped as a multiline string
135
function Lib.GetDebugInfo(instStr, maxDepth, tableLookupFunc)
1✔
136
        local inst = nil
137
        for obj, info in pairs(private.instInfo) do
5✔
138
                if info.str == instStr then
4✔
139
                        inst = obj
1✔
140
                        break
1✔
141
                end
142
        end
143
        if not inst then
2✔
144
                return nil
1✔
145
        end
146
        assert(not next(private.tempTable))
1✔
147
        private.InstDump(inst, private.tempTable, maxDepth, tableLookupFunc)
1✔
148
        local result = table.concat(private.tempTable, "\n")
1✔
149
        wipe(private.tempTable)
1✔
150
        return result
1✔
151
end
152

153

154

155
-- ============================================================================
156
-- Instance Metatable
157
-- ============================================================================
158

159
private.INST_MT = {
1✔
160
        __newindex = function(self, key, value)
161
                if RESERVED_KEYS[key] then
50✔
162
                        error("Can't set reserved key: "..tostring(key), 2)
1✔
163
                end
164
                if private.classInfo[self.__class].static[key] ~= nil then
49✔
165
                        private.classInfo[self.__class].static[key] = value
2✔
166
                elseif not private.instInfo[self].hasSuperclass then
47✔
167
                        -- We just set this directly on the instance table for better performance
168
                        rawset(self, key, value)
20✔
169
                else
170
                        private.instInfo[self].fields[key] = value
27✔
171
                end
172
        end,
173
        __index = function(self, key)
174
                -- This method is super optimized since it's used for every class instance access, meaning function calls and
175
                -- table lookup is kept to an absolute minimum, at the expense of readability and code reuse.
176
                local instInfo = private.instInfo[self]
272✔
177

178
                -- Check if this key is an instance field first, since this is the most common case
179
                local res = instInfo.fields[key]
272✔
180
                if res ~= nil then
272✔
181
                        instInfo.currentClass = nil
84✔
182
                        return res
84✔
183
                end
184

185
                -- Check if it's a special field / method
186
                if key == "__super" then
188✔
187
                        if not instInfo.hasSuperclass then
29✔
188
                                error("The class of this instance has no superclass", 2)
2✔
189
                        end
190
                        -- The class of the current class method we are in, or nil if we're not in a class method.
191
                        local methodClass = instInfo.methodClass
27✔
192
                        -- We can only access the superclass within a class method and will use the class which defined that method
193
                        -- as the base class to jump to the superclass of, regardless of what class the instance actually is.
194
                        if not methodClass then
27✔
195
                                error("The superclass can only be referenced within a class method", 2)
1✔
196
                        end
197
                        return private.InstAs(self, private.classInfo[instInfo.currentClass or methodClass].superclass)
26✔
198
                elseif key == "__as" then
159✔
199
                        return private.InstAs
17✔
200
                elseif key == "__closure" then
142✔
201
                        return private.InstClosure
11✔
202
                end
203

204
                -- Reset the current class since we're not continuing the __super chain
205
                local class = instInfo.currentClass or instInfo.class
131✔
206
                instInfo.currentClass = nil
131✔
207

208
                -- Check if this is a static key
209
                local classInfo = private.classInfo[class]
131✔
210
                res = classInfo.static[key]
131✔
211
                if res ~= nil then
131✔
212
                        return res
72✔
213
                end
214

215
                -- Check if it's a static field in the superclass
216
                local superStaticRes = classInfo.superStatic[key]
59✔
217
                if superStaticRes then
59✔
218
                        res = superStaticRes.value
39✔
219
                        return res
39✔
220
                end
221

222
                -- Check if this field has a default value
223
                res = DEFAULT_INST_FIELDS[key]
20✔
224
                if res ~= nil then
20✔
225
                        return res
15✔
226
                end
227

228
                return nil
5✔
229
        end,
230
        __eq = function(self, other)
231
                if self.__class ~= other.__class then
5✔
232
                        return false
2✔
233
                end
234
                return self:__equals(other)
3✔
235
        end,
236
        __tostring = function(self)
237
                return self:__tostring()
4✔
238
        end,
239
        __metatable = false,
1✔
240
}
1✔
241

242

243

244
-- ============================================================================
245
-- Class Metatable
246
-- ============================================================================
247

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

492

493

494
-- ============================================================================
495
-- Extension Metatable
496
-- ============================================================================
497

498
private.EXTENSION_MT = {
1✔
499
        __newindex = function(self, key, value)
500
                if type(key) ~= "string" then
2✔
501
                        error("Can't index class extension with non-string key", 2)
×
502
                elseif type(value) ~= "function" then
2✔
503
                        error("Can only add class methods via class extension", 2)
×
504
                elseif RESERVED_KEYS[key] then
2✔
505
                        error("Reserved word: "..key, 2)
×
506
                end
507
                local class = private.extensionInfo[self].class
2✔
508
                local classInfo = private.classInfo[class]
2✔
509
                if classInfo.subclassed then
2✔
510
                        error("Can't add extension methods after a class is subclassed", 2)
×
511
                end
512
                local testClass = class
2✔
513
                while testClass do
4✔
514
                        local testClassInfo = private.classInfo[testClass]
2✔
515
                        if testClassInfo.static[key] ~= nil then
2✔
516
                                error("Can't modify or override class members from extension", 2)
×
517
                        end
518
                        testClass = testClassInfo.superclass
2✔
519
                end
520
                -- Don't need to wrap extension methods because they are treated as if they are outside
521
                -- the class as far as access restrictions are concerned and don't need to worry about
522
                -- virtual methods since extensions only support non-subclassed classes.
523
                classInfo.static[key] = value
2✔
524
                -- Add the new method directly to all previously-created instances
525
                for inst in pairs(classInfo.instances) do
5✔
526
                        rawset(inst, key, value)
3✔
527
                end
528
        end,
529
        __index = function()
530
                error("Extension objects are write-only", 2)
×
531
        end,
532
        __tostring = function(self)
533
                return "classExtension:"..private.classInfo[private.extensionInfo[self].class].name
×
534
        end,
535
        __metatable = false,
1✔
536
}
1✔
537

538

539

540
-- ============================================================================
541
-- Helper Functions
542
-- ============================================================================
543

544
function private.ClassIsA(class, targetClass)
1✔
545
        while class do
4✔
546
                if class == targetClass then return true end
4✔
547
                class = class.__super
1✔
548
        end
549
end
550

551
function private.ClassExtend(class)
1✔
552
        local classInfo = private.classInfo[class]
1✔
553
        if not classInfo then
1✔
554
                error("__extend() must be called with `:` to pass the class", 2)
×
555
        elseif classInfo.subclassed then
1✔
556
                error("Can't add extension methods after a class is subclassed", 2)
×
557
        end
558
        classInfo.extended = true
1✔
559
        local extensionObj = setmetatable({}, private.EXTENSION_MT)
1✔
560
        private.extensionInfo[extensionObj] = {
1✔
561
                class = class,
1✔
562
        }
1✔
563
        return extensionObj
1✔
564
end
565

566
function private.InstMethodReturnHelper(class, instInfo, classInfo, ...)
1✔
567
        -- Reset methodClass and decrement inClassFunc now that the function returned
568
        instInfo.methodClass = class
122✔
569
        while classInfo do
319✔
570
                classInfo.inClassFunc = classInfo.inClassFunc - 1
197✔
571
                local superclass = classInfo.superclass
197✔
572
                classInfo = superclass and private.classInfo[superclass] or nil
197✔
573
        end
574
        return ...
122✔
575
end
576

577
function private.StaticFuncReturnHelper(classInfo, ...)
1✔
578
        -- Decrement inClassFunc now that the function returned
579
        while classInfo do
20✔
580
                classInfo.inClassFunc = classInfo.inClassFunc - 1
12✔
581
                local superclass = classInfo.superclass
12✔
582
                classInfo = superclass and private.classInfo[superclass] or nil
12✔
583
        end
584
        return ...
8✔
585
end
586

587
function private.InstIsA(inst, targetClass)
1✔
588
        return private.instInfo[inst].isClassLookup[targetClass]
2✔
589
end
590

591
function private.InstAs(inst, targetClass)
1✔
592
        local instInfo = private.instInfo[inst]
43✔
593
        -- Clear currentClass while we perform our checks so we can better recover from errors
594
        instInfo.currentClass = nil
43✔
595
        if not targetClass then
43✔
596
                error(format("Requested class does not exist"), 2)
4✔
597
        elseif not instInfo.isClassLookup[targetClass] then
39✔
598
                error(format("Object is not an instance of the requested class (%s)", tostring(targetClass)), 2)
3✔
599
        end
600
        -- For classes with no superclass, we don't go through the __index metamethod, so can't use __as
601
        if not instInfo.hasSuperclass then
36✔
602
                error("The class of this instance has no superclass", 2)
1✔
603
        end
604
        -- We can only access the superclass within a class method.
605
        if not instInfo.methodClass then
35✔
606
                error("The superclass can only be referenced within a class method", 2)
1✔
607
        end
608
        instInfo.currentClass = targetClass
34✔
609
        return inst
34✔
610
end
611

612
function private.InstClosure(inst, methodName)
1✔
613
        local instInfo = private.instInfo[inst]
11✔
614
        local methodClass = instInfo.methodClass
11✔
615
        if not methodClass then
11✔
616
                error("Closures can only be created within a class method", 2)
1✔
617
        elseif instInfo.currentClass then
10✔
618
                error("Cannot create closure as superclass", 2)
1✔
619
        end
620
        -- Check for this method on the class
621
        local classInfo = private.classInfo[instInfo.class]
9✔
622
        local methodFunc = classInfo.static[methodName]
9✔
623
        if methodFunc then
9✔
624
                -- If this method is private, make sure we're within the class
625
                if classInfo.methodProperties and classInfo.methodProperties[methodName] == "PRIVATE" and instInfo.class ~= methodClass then
5✔
626
                        error("Attempt to create closure for private virtual method", 2)
1✔
627
                end
628
        else
629
                -- Check for this method on the superclass
630
                local superInfo = classInfo.superStatic[methodName]
4✔
631
                if superInfo then
4✔
632
                        if superInfo.properties == "PRIVATE" and not private.classInfo[methodClass].static[methodName] then
3✔
633
                                error("Attempt to create closure for private superclass method", 2)
1✔
634
                        end
635
                        methodFunc = superInfo.value
2✔
636
                end
637
        end
638
        if type(methodFunc) ~= "function" then
7✔
639
                error("Attempt to create closure for non-method field", 2)
1✔
640
        end
641
        local methodClassInfo = private.classInfo[methodClass]
6✔
642
        local cacheKey = tostring(methodClass).."."..methodName
6✔
643
        if not instInfo.closures[cacheKey] then
6✔
644
                instInfo.closures[cacheKey] = function(...)
6✔
645
                        if instInfo.methodClass == methodClass then
8✔
646
                                -- We're already within a method of the class, so just call the method normally
647
                                return methodFunc(inst, ...)
5✔
648
                        else
649
                                -- Pretend we are within the class which created the closure
650
                                local prevClass = instInfo.methodClass
3✔
651
                                instInfo.methodClass = methodClass
3✔
652
                                local tempMethodClassInfo = methodClassInfo
3✔
653
                                while tempMethodClassInfo do
9✔
654
                                        tempMethodClassInfo.inClassFunc = tempMethodClassInfo.inClassFunc + 1
6✔
655
                                        local superclass = tempMethodClassInfo.superclass
6✔
656
                                        tempMethodClassInfo = superclass and private.classInfo[superclass] or nil
6✔
657
                                end
658
                                return private.InstMethodReturnHelper(prevClass, instInfo, methodClassInfo, methodFunc(inst, ...))
3✔
659
                        end
660
                end
661
        end
662
        return instInfo.closures[cacheKey]
6✔
663
end
664

665
function private.InstDump(inst, resultTbl, maxDepth, tableLookupFunc)
1✔
666
        local context = {
2✔
667
                resultTbl = resultTbl,
2✔
668
                maxDepth = maxDepth or 2,
2✔
669
                maxTableEntries = 100,
2✔
670
                tableLookupFunc = tableLookupFunc,
2✔
671
                tableRefs = {},
2✔
672
                depth = 0,
2✔
673
        }
674

675
        -- Build up our table references via a breadth-first search
676
        local bfsQueueKeyPath = {""}
2✔
677
        local bfsQueueDepth = {0}
2✔
678
        local bfsQueueValue = {inst}
2✔
679
        while #bfsQueueKeyPath > 0 do
18✔
680
                local keyPath = tremove(bfsQueueKeyPath, 1)
16✔
681
                local depth = tremove(bfsQueueDepth, 1)
16✔
682
                local value = tremove(bfsQueueValue, 1)
16✔
683
                if not context.tableRefs[value] then
16✔
684
                        context.tableRefs[value] = keyPath
14✔
685
                        if depth <= context.maxDepth and not private.classInfo[value] then
14✔
686
                                if private.instInfo[value] then
10✔
687
                                        local instInfo = private.instInfo[value]
2✔
688
                                        value = instInfo.hasSuperclass and instInfo.fields or value
2✔
689
                                end
690
                                for k, v in pairs(value) do
38✔
691
                                        if type(v) == "table" and (type(k) == "string" or type(k) == "number") and not strfind(k, DUMP_KEY_PATH_DELIM, nil, true) then
28✔
692
                                                tinsert(bfsQueueKeyPath, keyPath..DUMP_KEY_PATH_DELIM..k)
14✔
693
                                                tinsert(bfsQueueDepth, depth + 1)
14✔
694
                                                tinsert(bfsQueueValue, v)
14✔
695
                                        end
696
                                end
697
                        end
698
                end
699
        end
700

701
        private.InstDumpVariable("self", inst, context, "")
2✔
702
end
703

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

792
function private.InstDumpLine(line, context)
1✔
793
        line = strrep("  ", context.depth)..line
36✔
794
        if context.resultTbl then
36✔
795
                tinsert(context.resultTbl, line)
18✔
796
        else
797
                print(line)
18✔
798
        end
799
end
800

801
function private.InstDumpKeyValue(key, value, context)
1✔
802
        key = tostring(key)
26✔
803
        if key == "" then
26✔
804
                key = "\"\""
2✔
805
        end
806
        if not context.resultTbl then
26✔
807
                key = "|cff88ccff"..key.."|r"
13✔
808
        end
809
        value = tostring(value)
26✔
810
        local line = format("%s = %s", key, value)
26✔
811
        private.InstDumpLine(line, context)
26✔
812
end
813

814

815

816
-- ============================================================================
817
-- Initialization Code
818
-- ============================================================================
819

820
do
821
        -- Register with LibStub
822
        local libStubTbl = LibStub:NewLibrary("LibTSMClass", MINOR_REVISION)
1✔
823
        if libStubTbl then
1✔
824
                for k, v in pairs(Lib) do
4✔
825
                        libStubTbl[k] = v
3✔
826
                end
827
        end
828
        -- Return the library and our private table for unit testing
829
        return {Lib, private}
1✔
830
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