-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMayronObjects.lua
More file actions
2331 lines (1836 loc) · 77.7 KB
/
MayronObjects.lua
File metadata and controls
2331 lines (1836 loc) · 77.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- luacheck: ignore self 143 631
local addOnName = ...;
local type, tonumber, pairs = _G.type, _G.tonumber, _G.pairs;
_G.MayronObjects = _G.MayronObjects or {
versions = {};
NewFramework = function(self, version)
version = tonumber((version:gsub("%.+", "")));
self.last = version;
if (not self.versions[version]) then
local framework = {};
self.versions[version] = framework;
return framework;
end
end;
GetFramework = function(self, version)
if (version) then
version = version:gsub("%s+", ""):lower();
if (version == "latest") then
for key, _ in pairs(self.versions) do
version = key;
end
else
version = tonumber((version:gsub("%.+", "")));
end
self.last = version;
end
return self.versions[self.last];
end;
};
---@type MayronObjects
local Framework = _G.MayronObjects:NewFramework("3.1.5");
if (not Framework) then return end
local error, unpack, next, ipairs = _G.error, _G.unpack, _G.next, _G.ipairs;
local setmetatable, table, string = _G.setmetatable, _G.table, _G.string;
local getmetatable, select, pcall, strsplit = _G.getmetatable, _G.select, _G.pcall, _G.strsplit;
local tostring, collectgarbage, print, max = _G.tostring, _G.collectgarbage, _G.print, _G.math.max;
Framework.Types = {};
Framework.Types.Table = "table";
Framework.Types.Number = "number";
Framework.Types.Function = "function";
Framework.Types.Boolean = "boolean";
Framework.Types.String = "string";
Framework.Types.Nil = "nil";
-- holds class, instance, and interface controllers
-- used for controlling behaviour of these "entities"
local AllControllers = {};
-- handles validation for strongly-typed parameter and return values when calling a functions
local ProxyStack = {};
--[[
-- contains functions converted to strings to track function locations when inheritance is used
-- for example, if function cannot be found then control is switched to parent and function needs to be
-- temporarily stored during this process.
--]]
ProxyStack.funcStrings = {};
local Core = {}; -- holds all private core functions for internal use
Core.Framework = Framework;
Core.PREFIX = "|cffffcc00MayronObjects: |r"; -- this is used when printing out errors
Core.ExportedPackages = {}; -- contains all exported packages
Core.DebugMode = false;
--[[
-- need a reference for this to hack around the manual exporting process
-- (exporting the package class but it's already a package...)
--]]
---@class Package
local Package;
--------------------------------------------
-- MayronObjects Functions
--------------------------------------------
function Framework:IsTable(value)
return type(value) == Framework.Types.Table;
end
function Framework:IsNumber(value)
return type(value) == Framework.Types.Number;
end
function Framework:IsFunction(value)
return type(value) == Framework.Types.Function;
end
function Framework:IsBoolean(value)
return type(value) == Framework.Types.Boolean;
end
function Framework:IsString(value)
return type(value) == Framework.Types.String;
end
function Framework:IsNil(value)
return type(value) == Framework.Types.Nil;
end
function Framework:IsObject(value)
if (not Framework:IsTable(value)) then
return false;
end
return (Core:GetController(value, true) ~= nil);
end
---@param value any @Any value to check whether it is of the expected widget type.
---@param widgetType string @An optional widget type to test if the value is that type of widget.
---@return boolean @true if the value is a Blizzard widgets, such as a Frame or Button.
function Framework:IsWidget(value, widgetType)
if (not Framework:IsTable(value)) then
return false;
end
local isObject = (Core:GetController(value, true) ~= nil);
if (isObject) then
return false;
end
local isWidget = (value.GetObjectType ~= nil and value.GetName ~= nil);
if (isWidget and self:IsString(widgetType)) then
isWidget = value:GetObjectType() == widgetType;
end
return isWidget;
end
function Framework:IsStringNilOrWhiteSpace(value)
return Core:IsStringNilOrWhiteSpace(value);
end
-- Helper function to check if value is a specified type
-- @param value: The value to check the type of (can be nil)
-- @param expectedTypeName: The exact type to check for (can be ObjectType)
-- @return (boolean): Returns true if the value type matches the specified type
function Framework:IsType(value, expectedTypeName)
return Core:IsMatchingType(value, expectedTypeName);
end
do
local wrappers = {};
local lives = {};
local pendingClean;
local C_Timer = _G.C_Timer;
local function CleanWrappers()
for key, value in pairs(lives) do
lives[key] = value - 1;
end
local removed = false;
for key, wrapper in pairs(wrappers) do
if (lives[key] <= 0) then
lives[key] = nil;
wrappers[key] = nil;
setmetatable(wrapper, nil);
Framework:EmptyTable(wrapper);
removed = true;
end
end
if (removed) then
collectgarbage("collect");
end
if (next(wrappers)) then
C_Timer.After(10, CleanWrappers);
else
pendingClean = nil;
end
end
-- Only iterates over values found in table and will cut off trailing `nil` values
function Framework:IterateValues(...)
local index = 0;
local args = self:PopTable(...);
return function()
index = index + 1;
if (index <= #args) then
return index, args[index];
else
-- reached end of wrapper so finish looping and clean up
Framework:PushTable(args);
end
end
end
-- iterates over all arguments in a variable argument list, including explicit `nil` CopyTableValues
-- does not trim off trailing `nil` values.
function Framework:IterateArgs(...)
local index = 0;
local size = select("#", ...); -- can only accurately get size of vararg
if (size == 1 and (select(1, ...)) == nil) then
print("error");
error("wrong")
end
local args = self:PopTable(...); -- may contain `nil` values, so we cannot use `#`.
return function()
index = index + 1;
if (index <= size) then
return index, args[index];
else
-- reached end of wrapper so finish looping and clean up
Framework:PushTable(args);
end
end
end
local function PushTable(wrapper)
local key = tostring(wrapper);
if (not wrappers[key]) then
wrappers[key] = wrapper;
lives[key] = 3;
end
if (not pendingClean) then
pendingClean = true;
C_Timer.After(10, CleanWrappers);
end
end
---@return table @An empty table
function Framework:PopTable(...)
-- get wrapper before iterating
local _, wrapper = next(wrappers);
if (Framework:IsTable(wrapper)) then
local key = tostring(wrapper);
lives[key] = nil;
wrappers[key] = nil;
-- empty table (incase tk.Tables:UnpackTable was used)
setmetatable(wrapper, nil);
Framework:EmptyTable(wrapper);
else
-- create new wrapper (required if a for-loop call to
-- IterateArgs is nested inside another IterateArgs call)
wrapper = {};
end
local length = select("#", ...);
-- add all values from vararg to table:
for index = 1, length do
wrapper[index] = (select(index, ...));
end
return wrapper, length;
end
---@param wrapper table @A table to be added to the stack. The table is emptied and detached from any meta-table
---@param pushSubTables boolean|function @Whether sub tables found in the table should also be pushed to the stack
function Framework:PushTable(wrapper, pushSubTables, path)
if (not self:IsTable(wrapper) or self:IsWidget(wrapper)) then
return;
end
local push = true;
for key, _ in pairs(wrapper) do
if (pushSubTables and self:IsTable(wrapper[key]) and not self:IsWidget(wrapper)) then
local nextPath;
if (path) then
nextPath = string.format("%s.%s", path, tostring(key));
else
nextPath = tostring(key);
end
if (self:IsFunction(pushSubTables)) then
push = pushSubTables(wrapper, wrapper[key], key, nextPath);
end
if (push) then
self:PushTable(wrapper[key], pushSubTables, nextPath);
end
end
wrapper[key] = nil;
end
if (push) then
setmetatable(wrapper, nil);
PushTable(wrapper);
end
end
---@param wrapper table @A table to be unpacked and pushed to the stack to be emptied later.
---@param doNotPushTable boolean @If true, the table will not be pushed
---@param length number @An optional number to specify the known length of the table (in case it was a vararg and length is important)
function Framework:UnpackTable(wrapper, doNotPushTable, length)
if (not self:IsTable(wrapper)) then return end
if (not length) then
-- because wrapper is a table containing nil values (not a correct sequence)
-- we cannot use "#wrapper" or select("#", unpack(wrapper)) and we lose
-- trailing `nil` values when using pairs:
for id, _ in pairs(wrapper) do
length = id;
end
end
if (not doNotPushTable) then
PushTable(wrapper);
end
if (not Framework:IsNumber(length) or length < 1) then
return unpack(wrapper);
else
return unpack(wrapper, 1, length);
end
end
end
---A helper function to empty a table.
---@param tbl table @The table to empty.
function Framework:EmptyTable(tbl)
for key, _ in pairs(tbl) do
tbl[key] = nil;
end
end
---A helper function to add all values from one table to another table.
---Also works with nested tables with matching keys.
---@param tbl table @The table to add all values into from the other table (otherTbl).
---@param otherTbl table @The other table to copy values from and place into the first table (tbl).
---@param preserveOldValue boolean @If true and a key is found in both tables, the value will not be
---overridden by the one in the other table (otherTbl).
function Framework:FillTable(tbl, otherTbl, preserveOldValue)
for key, value in pairs(otherTbl) do
if (self:IsTable(tbl[key]) and self:IsTable(value)) then
self:FillTable(tbl[key], value, preserveOldValue);
elseif (not preserveOldValue or self:IsNil(tbl[key])) then
if (self:IsTable(value)) then
tbl[key] = self:PopTable();
self:FillTable(tbl[key], value);
else
tbl[key] = value;
end
end
end
end
---A helper function to print a table's contents.
---@param tbl table @The table to print.
---@param depth number @An optional number specifying the depth of sub-tables to traverse through and print.
---@param spaces number @An optional number specifying the spaces to print to intent nested values inside a table.
---@param n number @Do NOT manually set this. This controls formatting through recursion.
function Framework:PrintTable(tbl, depth, spaces, n)
local value = self:ToLongString(tbl, depth, spaces, nil, n);
-- cannot print the full string because Blizzard's chat frame messes up spacing when it encounters '\n'
for _, line in self:IterateArgs(strsplit("\n", value)) do
print(line);
end
end
---A helper function to return the contents of a table as a long string, similar to
---what the PrintTable utility method prints except it does not print it.
---@param tbl table @The table to convert to a long string.
---@param depth number @An optional number specifying the depth of sub-tables to traverse through and append to the long string.
---@param spaces number @An optional number specifying the spaces to print to intent nested values inside a table.
---@param n number @Do NOT manually set this. This controls formatting through recursion.
---@return string @A long string containing the contents of the table.
function Framework:ToLongString(tbl, depth, spaces, result, n)
result = result or "";
n = n or 0;
spaces = spaces or 2;
depth = depth or 5;
if (depth == 0) then
return string.format("%s\n%s", result, string.rep(' ', n).."...");
end
for key, value in pairs(tbl) do
if (key and self:IsNumber(key) or self:IsString(key)) then
key = string.format("[\"%s\"]", key);
if (self:IsTable(value)) then
if (#result > 0) then
result = string.format("%s\n%s", result, string.rep(' ', n));
else
result = string.rep(' ', n);
end
if (next(value)) then
if (depth == 1) then
result = string.format("%s%s = { ... },", result, key);
else
result = string.format("%s%s = {", result, key);
result = self:ToLongString(value, depth - 1, spaces, result, n + spaces);
result = string.format("%s\n%s},", result, string.rep(' ', n));
end
else
result = string.format("%s%s%s = {},", result, string.rep(' ', n), key);
end
else
if (self:IsString(value)) then
value = string.format("\"%s\"", value);
else
value = tostring(value);
end
result = string.format("%s\n%s%s = %s,", result, string.rep(' ', n), key, value);
end
end
end
return result;
end
---@param packageName string @The name of the package.
---@param namespace string @The parent package namespace. Example: "Framework.System.package".
---@return Package @Returns a package object.
function Framework:CreatePackage(packageName, namespace)
local newPackage = Package(packageName, namespace);
Core:Assert(newPackage ~= nil, "Failed to create new Package '%s'", packageName);
-- export the package only if a namespace is supplied
if (not Core:IsStringNilOrWhiteSpace(namespace)) then
self:Export(newPackage, namespace);
end
return newPackage;
end
---@param namespace string @The entity namespace (required for locating it). (an entity = a package, class or interface).
---@param silent boolean @If true, no error will be triggered if the entity cannot be found.
---@return Package|Class|Interface @Returns the found entity (or false if silent).
function Framework:Import(namespace, silent)
local entity;
local currentNamespace = "";
local nodes = Framework:PopTable(strsplit(".", namespace));
for id, key in ipairs(nodes) do
Core:Assert(not Core:IsStringNilOrWhiteSpace(key), "Import - bad argument #1 (invalid entity name).");
if (id > 1) then
currentNamespace = string.format("%s.%s", currentNamespace, key);
entity = entity:Get(key, silent);
else
currentNamespace = key;
entity = Core.ExportedPackages[key];
end
if (not entity and silent) then
return false;
end
if (id < #nodes) then
Core:Assert(entity, "Import - bad argument #1 ('%s' package not found).", currentNamespace);
else
Core:Assert(entity, "Import - bad argument #1 ('%s' entity not found).", currentNamespace);
end
end
Framework:PushTable(nodes);
if (not silent) then
local controller = Core:GetController(entity, true);
Core:Assert(controller or entity.IsObjectType and entity:IsObjectType("Package"),
"Import - bad argument #1 (invalid namespace '%s').", namespace);
Core:Assert(entity ~= Core.ExportedPackages, "Import - bad argument #1 ('%s' package not found).", namespace);
end
return entity;
end
---@param namespace string @(Optional) The package namespace (required for locating and importing it).
---@param package Package @A package instance object.
function Framework:Export(package, namespace)
local classController = Core:GetController(package);
Core:Assert(classController and classController.IsPackage, "Export - bad argument #1 (package expected)");
if (not namespace) then
local key = package:GetName();
Core.ExportedPackages[key] = package;
return
end
local parentPackage;
for id, key in self:IterateArgs(strsplit(".", namespace)) do
Core:Assert(not Core:IsStringNilOrWhiteSpace(key), "Export - bad argument #2 (invalid namespace).");
key = key:gsub("%s+", "");
if (id > 1) then
if (not parentPackage:Get(key)) then
-- auto-create empty packages if not found in namespace
parentPackage:AddSubPackage(Framework:CreatePackage(key));
end
parentPackage = parentPackage:Get(key);
else
-- auto-create empty packages if not found in namespace
Core.ExportedPackages[key] = Core.ExportedPackages[key] or Framework:CreatePackage(key);
parentPackage = Core.ExportedPackages[key];
end
end
-- add package to the last (parent) package specified in the namespace
parentPackage:AddSubPackage(package, namespace);
end
---@param silent boolean @True if errors should be cause in the error log instead of triggering.
function Framework:SetSilentErrors(silent)
Core.silent = silent;
end
---@return table @Contains index/string pairs of errors caught while in silent mode.
function Framework:GetErrorLog()
Core.errorLog = Core.errorLog or {};
return Core.errorLog;
end
---Empties the error log table.
function Framework:FlushErrorLog()
if (Core.errorLog) then
Framework:EmptyTable(Core.errorLog);
end
end
---@return number @The total number of errors caught while in silent mode.
function Framework:GetNumErrors()
return (Core.errorLog and #Core.errorLog) or 0;
end
---Proxy function to allow outside users to use Core:Assert()
---@param condition boolean @A predicate to evaluate.
---@param errorMessage string @(Optional) An error message to throw if condition is evaluated to false.
---@vararg any @A list of arguments to be inserted into the error message using string.format.
function Framework:Assert(condition, errorMessage, ...)
Core:Assert(condition, errorMessage, ...);
end
---Proxy function to allow outside users to use Core:Error()
---@param errorMessage string @The error message to throw.
---@vararg any @A list of arguments to be inserted into the error message using string.format.
function Framework:Error(errorMessage, ...)
Core:Error(errorMessage, ...);
end
---Attach an error handling function to call when an error occurs to be handled manually.
---@param errorHandler function @The error handler callback function.
function Framework:SetErrorHandler(errorHandler)
Core.errorHandler = errorHandler;
end
---Do NOT use this unless you are a MayronObjects developer.
---@param debug boolean @Set the Frameworkrary to debug mode.
function Framework:SetDebugMode(debug)
Core.DebugMode = debug;
end
-------------------------------------
-- ProxyStack
-------------------------------------
-- Pushes the proxy function back into the stack object once no longer needed.
-- Also, resets the state of the proxy function for future use.
-- @param proxyFunc (function) - a proxy function returned from ProxyStack:Pop();
function ProxyStack:Push(proxyObject)
self[#self + 1] = proxyObject;
proxyObject.object = nil;
proxyObject.key = nil;
proxyObject.self = nil;
proxyObject.privateData = nil;
proxyObject.controller = nil;
end
function ProxyStack:Pop()
if (#self == 0) then
return Framework:PopTable();
end
local proxyObject = self[#self];
self[#self] = nil;
return proxyObject;
end
-- intercepts function calls on classes and instance objects and returns a proxy function used for validation.
-- @param object (table) - a table containing all functions assigned to a class or interface.
-- @param key (string) - the function name/key being called.
-- @param self (table) - the instance or class object originally being called with the function name/key.
-- @param controller (table) - the entities meta-data (stores validation rules and more).
-- @return proxyFunc (function) - the proxy function is returned and called instead of the real function.
local function CreateProxyObject(object, key, self, controller, privateData)
local proxyObject = ProxyStack:Pop();
proxyObject.object = object;
proxyObject.key = key;
proxyObject.self = self;
proxyObject.controller = controller;
proxyObject.privateData = privateData;
-- we need multiple Run functions in case 1 function calls another (Run is never removed after being assigned)
proxyObject.run = proxyObject.run or function(_, ...)
-- Validate parameters passed to function
local definition, errorMessage = Core:GetParamsDefinition(proxyObject);
local args, argsLength = Core:ValidateFunctionCall(definition, errorMessage, ...);
-- Silent errors
if (not Framework:IsTable(args)) then return end
if (not Framework:IsTable(proxyObject.privateData) and not proxyObject.key:match("Static.")) then
if (proxyObject.controller.isInterface) then
Core:Error("%s.%s is an interface function and must be implemented and invoked by an instance object.",
proxyObject.controller.objectName, proxyObject.key);
else
Core:Error("%s.%s is a non-static function and must be invoked by an instance object.",
proxyObject.controller.objectName, proxyObject.key);
end
return
end
definition, errorMessage = Core:GetReturnsDefinition(proxyObject);
if (not(Framework:IsFunction(proxyObject.object[proxyObject.key]))) then
Core:Error("Could not find function '%s' for object '%s'",
proxyObject.key, proxyObject.controller.objectName);
return
end
-- execute attributes:
local attributes = Core:GetAttributes(proxyObject);
if (Framework:IsTable(attributes)) then
for _, attribute in ipairs(attributes) do
if (not attribute:OnExecute(proxyObject.self, proxyObject.privateData, proxyObject.key, unpack(args, 1, argsLength))) then
Framework:PushTable(args);
return -- if attribute returns false, do no move onto the next attribute and do not call function
end
end
end
local returnValues, returnValuesLength;
if (proxyObject.privateData) then
-- Validate return values received after calling the function
returnValues, returnValuesLength = Core:ValidateFunctionCall(definition, errorMessage,
-- call function here:
proxyObject.object[proxyObject.key](proxyObject.self, proxyObject.privateData, unpack(args, 1, argsLength)));
else
-- Validate return values received after calling the STATIC function
returnValues, returnValuesLength = Core:ValidateFunctionCall(definition, errorMessage,
-- call function here:
proxyObject.object[proxyObject.key](proxyObject.self, unpack(args, 1, argsLength)));
end
Framework:PushTable(args);
-- Silent errors
if (not Framework:IsTable(returnValues)) then return end
if (proxyObject.key ~= "Destroy") then
local instanceController = Core:GetController(proxyObject.self, true);
if (instanceController and Framework:IsTable(instanceController.UsingParentControllers)) then
-- might have been destroyed during the function call
Framework:PushTable(instanceController.UsingParentControllers);
instanceController.UsingParentControllers = nil;
end
end
ProxyStack:Push(proxyObject);
if (returnValuesLength == 0) then
Framework:PushTable(returnValues);
return
end
return Framework:UnpackTable(returnValues, false, returnValuesLength);
end
ProxyStack.funcStrings[tostring(proxyObject.run)] = proxyObject;
return proxyObject.run;
end
-- Needed for editing the proxyObject properties because ProxyStack:Pop only returns the runnable function
-- @param func (function) - converts function to string to be used as a key to access the corresponding proxyObject.
-- @return proxyFunc (function) - the proxyObject.
local function GetStoredProxyObject(proxyFunc)
return ProxyStack.funcStrings[tostring(proxyFunc)];
end
-------------------------------------
-- Core Functions
-------------------------------------
do
local proxyClassMT = {}; -- acts as a filter to protect invalid keys from being indexed into Class
-- ProxyClassMT meta-methods ------------------------
proxyClassMT.__call = function(self, ...)
local classController = Core:GetController(self);
return Core:CreateInstance(classController, ...);
end
proxyClassMT.__index = function(self, key)
local classController = Core:GetController(self);
local class = classController.class;
local value = class[key]; -- get the real value
if (Framework:IsFunction(value)) then
-- get a proxy function object to validate function params and return values
value = CreateProxyObject(class, key, self, classController);
elseif (value == nil) then
-- no real value stored in Class
if (classController.parentProxyClass) then
-- search parent class instead
value = classController.parentProxyClass[key];
if (Framework:IsFunction(value)) then
-- need to update the "self" reference to use this class, not the parent!
local proxyObject = GetStoredProxyObject(value);
proxyObject.self = self;
end
end
if (value == nil and classController.objectName == "FrameWrapper" and key ~= "GetFrame") then
-- note: cannot check if frame has key here...
-- if value is still not found and object has a GetFrame method (usually
-- from inheriting FrameWrapper) then index the frame
value = CreateProxyObject(class, "GetFrame", self, classController);
end
end
if (classController.UsingChild and Framework:IsFunction(value)) then
local isVirtual = classController.virtualFunctions and classController.virtualFunctions[key];
if (isVirtual) then
-- if Object:Parent() was used, call parent function with the child as the reference
local child = classController.UsingChild;
local childController = Core:GetController(child);
local proxyObject = GetStoredProxyObject(value);
proxyObject.privateData = Core:GetPrivateInstanceData(child, childController);
end
end
return value;
end
proxyClassMT.__newindex = function(self, key, value)
local classController = Core:GetController(self);
if (key == "Static" or key == "Private") then
-- not allowed to override these Class properties
Core:Error("%s.%s are reserved class properties.", classController.objectName, key);
return;
end
if (classController.isProtected) then
Core:Error("%s is protected.", classController.objectName);
end
if (Framework:IsFunction(value)) then
-- Adds temporary definition info to ClassController.definitions table
Core:AttachFunctionDefinition(classController, key);
classController.class[key] = value;
else
Core:Error("Failed to add non-function value to %s.%s. Use the Static table instead.", classController.objectName, key);
end
end
proxyClassMT.__tostring = function(self)
setmetatable(self, nil);
local classController = AllControllers[tostring(self)];
local str = tostring(self):gsub(Framework.Types.Table, string.format("<Class> %s", classController.objectName));
setmetatable(self, proxyClassMT);
return str;
end
local proxyPrivateMT = {};
proxyPrivateMT.__newindex = function(self, key, value)
local classController = Core:GetController(self);
key = string.format("Private.%s", key);
if (classController.isProtected) then
Core:Error("%s is protected.", classController.objectName);
end
if (Framework:IsFunction(value)) then
-- Adds temporary definition info to ClassController.definitions table
Core:AttachFunctionDefinition(classController, key);
classController.privateFunctions[key] = value;
else
-- get a proxy function object to validate function params and return values
Core:Error("Only private functions should be added to this table.");
end
end
proxyPrivateMT.__index = function(self, key)
local classController = Core:GetController(self);
key = string.format("Private.%s", key);
local value = classController.privateFunctions[key]; -- get the real value
if (Framework:IsFunction(value)) then
-- get a proxy function object to validate function params and return values
Core:Error("%s.%s is a non-static function and must be invoked by an instance object.",
classController.objectName, key);
return
end
return value;
end
local proxyStaticMT = {};
proxyStaticMT.__newindex = function(self, key, value)
local classController = Core:GetController(self);
key = string.format("Static.%s", key);
if (classController.isProtected) then
Core:Error("%s is protected.", classController.objectName);
end
if (Framework:IsFunction(value)) then
-- Adds temporary definition info to ClassController.definitions table
Core:AttachFunctionDefinition(classController, key);
classController.staticData[key] = value;
end
classController.staticData[key] = value;
end
proxyStaticMT.__index = function(self, key)
local classController = Core:GetController(self);
key = string.format("Static.%s", key);
local value = classController.staticData[key]; -- get the real value
if (Framework:IsFunction(value)) then
return CreateProxyObject(classController.staticData, key, self, classController);
end
return value;
end
function Core:CreateClass(package, packageData, className, parentProxyClass, ...)
local class = Framework:PopTable(); -- stores real table indexes (once proxy has completed evaluating data)
local proxyClass = Framework:PopTable(); -- enforces __newindex meta-method to always be called (new indexes, if valid, are added to Class instead)
local definitions = Framework:PopTable(); -- function definitions for params and return values
local friends = Framework:PopTable(); -- friend classes can access instance private data of this class
local classController = Framework:PopTable(); -- holds special Framework data to control class
local privateFunctions = Framework:PopTable(); -- holds all private class functions
local staticData = Framework:PopTable(); -- holds all static class functions
classController.isClass = true;
classController.objectName = className;
classController.proxy = proxyClass;
classController.definitions = definitions;
classController.class = class;
classController.privateFunctions = privateFunctions;
classController.staticData = staticData;
-- protected table for assigning Static functions
class.Static = setmetatable(Framework:PopTable(), proxyStaticMT);
class.Private = setmetatable(Framework:PopTable(), proxyPrivateMT);
AllControllers[tostring(class.Private)] = classController;
AllControllers[tostring(class.Static)] = classController;
if (package and packageData) then
-- link new class to package
classController.package = package; -- only used for GetPackage()
classController.packageData = packageData;
packageData.entities[className] = proxyClass;
if (className:match("<") and className:match(">")) then
classController.isGenericType = true;
classController.genericTypes = self:GetGenericTypesFromClassName(className);
end
self:SetParentClass(classController, parentProxyClass);
self:SetInterfaces(classController, ...);
-- ProxyClass functions --------------------------
class.Static.AddFriendClass = function(_, friendClassName)
friends[friendClassName] = true;
end
class.Static.IsFriendClass = function(_, friendClassName)
if (friendClassName == className) then
return true;
end
return friends[friendClassName];
end
class.Static.OnIndexChanged = function(_, callback)
classController.indexChangedCallback = callback;
end
class.Static.OnIndexChanging = function(_, callback)
classController.indexChangingCallback = callback;
end
class.Static.OnIndexed = function(_, callback)
classController.indexedCallback = callback;
end
class.Static.OnIndexing = function(_, callback)
classController.indexingCallback = callback;
end
proxyClass.Of = function(_, ...)
Core:Assert(classController.isGenericType, "%s is not a generic class", className);
classController.tempRealGenericTypes = Framework:PopTable();
for id, realType in Framework:IterateArgs(...) do
if (Framework:IsObject(realType)) then
local controller = Core:GetController(realType);
realType = controller.objectName;
end
classController.tempRealGenericTypes[id] = (realType:gsub("%s+", ""));
end
return proxyClass;
end
else
-- creating the Package class (cannot assign it to a package
-- instance as Package class does not exist!)
classController.IsPackage = true;
end
AllControllers[tostring(proxyClass)] = classController;
setmetatable(proxyClass, proxyClassMT);
return proxyClass;
end
end
do
local proxyInstanceMT = {}; -- acts as a filter to protect invalid keys from being indexed into Instance
local GetFrame = "GetFrame";
local innerValues = {};
local frameWrapperFunction = function(_, ...)
-- call the frame (a blizzard widget) here
return innerValues.frame[innerValues.key](innerValues.frame, ...);
end
local function GetFrameWrapperFunction(value, key)
-- ProxyClass changed key to GetFrame during __index meta-method call
local frame = value(); -- call the proxyObject.Run function here to get the frame
if (not (Framework:IsTable(frame) and frame.GetObjectType)) then
-- might be a property we are searching for, so do not throw an error!
return
end
if (frame[key]) then
-- if the frame has the key we are trying to get...
if (Framework:IsFunction(frame[key])) then
innerValues.frame = frame;
innerValues.key = key;
value = frameWrapperFunction;
else
value = frame[key];
end
else
value = nil; -- no frame found
end