forked from XINCGer/Unity3DTraining
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathColaPlus.lua
More file actions
1605 lines (1348 loc) · 41.5 KB
/
Copy pathColaPlus.lua
File metadata and controls
1605 lines (1348 loc) · 41.5 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
--[[
Colaplus: Lua高级面向对象开发插件
]]
local ColaPlus = {}
----------------------------------------
--
-- external functions
--
----------------------------------------
local rawget = rawget
local type = type
local pairs = pairs
local setmetatable = setmetatable
local getmetatable = getmetatable
local tostring = tostring
local error = error
local select = select
local assert = assert
local require = require
local pcall = pcall
local debug = debug
-- debug
local _G = _G
--~ local _error = error
--~ local function error (what)
--~ return _error(what, 2)
--~ end
local _ENV = nil -- help to do spelling checking, compatible with lua 5.1
----------------------------------------
--
-- Utilities part 1
--
----------------------------------------
local function createProxy (metatable)
return setmetatable({}, metatable)
end
local function shallowCopy (destTable, sourceTable)
for k, v in pairs(sourceTable) do
destTable[k] = v
end
end
local function argError (iArg, funcName, needs, gets, errLevel)
error(("bad argument #%d to '%s' (%s expected, got %s)")
:format(iArg, funcName, needs, gets), errLevel + 1)
end
local function argListError (iArg, memberName, needs, gets, errLevel)
if gets == nil then
error(([[bad argument #%d to argument list of %s (%s)]])
:format(iArg, memberName, needs), errLevel + 1)
else
error(([[bad argument #%d to argument list of %s (%s expected, got %s)]])
:format(iArg, memberName, needs, gets), errLevel + 1)
end
end
local function initValueError (fieldName, needs, gets, errLevel)
if gets == nil then
error(([[bad inital value to field '%s' (%s)]])
:format(fieldName, needs), errLevel + 1)
else
error(([[bad inital value to field '%s' (%s expected, got %s)]])
:format(fieldName, needs, gets), errLevel + 1)
end
end
----------------------------------------
--
-- ColaPlus config
--
----------------------------------------
local config =
{
--default config
reflection = false,
declare_checking = true,
accessing_checking = true,
calling_checking = true,
reload = false,
}
--
-- load config
--
local loadedConfig
do
-- load from module ColaPlus_config
local currentModule = ...
if currentModule ~= nil then
local configModule = currentModule .. "_config"
local bRet, result = pcall(require, configModule)
if bRet then
if type(result) ~= "table" then
error("module ColaPlus_config should return a table, got: " .. type(result))
end
loadedConfig = result
end
end
end
if loadedConfig ~= nil then
shallowCopy(config, loadedConfig)
end
--
-- feature config
--
local feature_reflection = config.reflection
local feature_declare_checking = config.declare_checking
local feature_accessing_checking = config.accessing_checking
local feature_calling_checking = config.calling_checking
local feature_reload = config.reload
--
-- derived feature config
--
local feature_member_info = feature_declare_checking or feature_accessing_checking
----------------------------------------
--
-- ColaPlus global variables
--
----------------------------------------
-- set flag that ColaPlus library is initializing
local bInitializingColaPlus = true
-- to determine value is ColaPlus object
local ColaPlusObjectMagic = {}
-- to determine value is ColaPlus type table
local ColaPlusTypeTableMagic = {}
-- to control function wrapper
local ColaPlusFunctionWrapperControlMagic = {}
-- mapping type name to type table
local typeNameToTableMap = {}
----------------------------------------
--
-- Utilities part 2
--
----------------------------------------
local basicTypeSet =
{
["nil"] = true,
["number"] = true,
["string"] = true,
["boolean"] = true,
["table"] = true,
["function"] = true,
["thread"] = true,
["userdata"] = true,
["dynamic"] = true, --any type (lua default style)
}
local primaryTypeSet =
{
["nil"] = true,
["number"] = true,
["string"] = true,
["boolean"] = true,
}
local nonNilPrimaryTypeSet =
{
["number"] = true,
["string"] = true,
["boolean"] = true,
}
local function getTypeTableMeta (typeTable)
if type(typeTable) ~= "table" then
return nil
end
local meta = getmetatable(typeTable)
--check magic
if meta == nil or meta.magic ~= ColaPlusTypeTableMagic then
return nil
end
return meta
end
local getTypeTableMetaNoCheck = getmetatable
local function getObjectMeta (obj)
if type(obj) ~= "table" then
return nil
end
--check magic
local meta = getmetatable(obj)
if meta == nil or meta.magic ~= ColaPlusObjectMagic then
return nil
end
return meta
end
local getObjectMetaNoCheck = getmetatable
local function getObjectTypeTable (obj)
return getObjectMetaNoCheck(obj).typeTable
end
local function getObjectTypeMeta (obj)
return getTypeTableMetaNoCheck(getObjectTypeTable(obj))
end
local function checkTypeTable (typeTable, iArg, who, what, errLevel)
if getTypeTableMeta(typeTable) == nil then
argError(iArg, funcName, "type table", type(typeTable), errLevel+1)
end
end
local function formatTypeName (typeValue)
if typeValue == nil then
return "<none>"
elseif type(typeValue) == "string" then
return '"' .. typeValue .. '"'
else
return tostring(typeValue)
end
end
local function formatObjectTypeName (object)
if ColaPlus.is(object, ColaPlus.Object) then
return tostring(object:getTypeTable())
else
return '"' .. type(object) .. '"'
end
end
local function checkValidArgType (typeValue, iParam, memberName, errLevel)
if type(typeValue) == "string" then
if not basicTypeSet[typeValue] then
argListError(iParam, memberName, "vaild basic type name", '"'..typeValue..'"', errLevel+1)
end
else
if getTypeTableMeta(typeValue) == nil then
argListError(iParam, memberName, "type table", type(typeValue), errLevel+1)
end
end
end
local function isTypeCompatible (value, needType)
if needType == "dynamic" then
return true
elseif type(needType) == "string" then
if nonNilPrimaryTypeSet[needType] then
return type(value) == needType
else
-- nilable type is compatible with nil
return value == nil or type(value) == needType
end
else
return value == nil or ColaPlus.is(value, needType)
end
end
local function checkValueCompatible (value, needType, format, who, errorLevel)
if not isTypeCompatible(value, needType) then
local what = format:format(who)
error(([[bad %s (%s expected, got %s)]])
:format(what, formatTypeName(needType), formatObjectTypeName(value)), errorLevel + 1)
end
end
local function isTypeTableInterface (typeTable)
return getTypeTableMetaNoCheck(typeTable).isInterface
end
----------------------------------------
--
-- type creation
--
----------------------------------------
local function inheritMemberInfo (derivedMemberInfo, baseMemberInfo)
for name, info in pairs(baseMemberInfo) do
if info.inheritable then
derivedMemberInfo[name] = info
end
end
end
-- copy base members to derived type meta
local function inheritMembers (derivedMeta, baseTypeTable)
-- inherit from baseTypeTable
local baseMeta = getTypeTableMetaNoCheck(baseTypeTable)
shallowCopy(derivedMeta.fields, baseMeta.fields)
shallowCopy(derivedMeta.constructors, baseMeta.constructors)
shallowCopy(derivedMeta.methods, baseMeta.methods)
shallowCopy(derivedMeta.abstractMethods, baseMeta.abstractMethods)
shallowCopy(derivedMeta.staticMembers, baseMeta.staticMembers)
shallowCopy(derivedMeta.compatibleTypes, baseMeta.compatibleTypes)
if feature_member_info then
inheritMemberInfo(derivedMeta.memberInfoMap, baseMeta.memberInfoMap)
end
end
-- param paramList: { param1, param2, ..., "=>", ret1, ret2, ... }
-- return: { [n] = paramN, [-n] = retN }
local function checkMethodParamAndMakeList (paramCount, paramList, methodName, errorLevel)
local result = {}
local bReturnPart = false
local iSeperator = -1
local bGotParamValist = false
local bGotReturnValist = false
for i = 1, paramCount do
local inParam = paramList[i]
if inParam == "=>" then
bReturnPart = true
iSeperator = i
elseif inParam == "varlist" then
if bReturnPart then
bGotReturnValist = true
result[-(i-iSeperator)] = inParam -- last return value type
else
bGotParamValist = true
result[i] = inParam -- last param value type
end
else
checkValidArgType(inParam, i, methodName, errorLevel+1)
if bReturnPart then
if bGotReturnValist then
argListError(i, methodName, '"varlist" must be the last return value type', nil, errorLevel + 1)
end
result[-(i-iSeperator)] = inParam -- a return value type
else
if bGotParamValist then
argListError(i, methodName, '"varlist" must be the last param value type', nil, errorLevel + 1)
end
result[i] = inParam -- a param value type
end
end
end
return result
end
-- return diff index, or nil if equal
local function compareSignature (signatureLeft, signatureRight)
local iParam = 1
repeat
local paramLeft = signatureLeft[iParam]
local paramRight = signatureRight[iParam]
if paramLeft ~= paramRight then
return iParam
end
iParam = iParam + 1
until paramLeft == nil
local iReturn = 1
repeat
local returnLeft = signatureLeft[-iReturn]
local returnRight = signatureRight[-iReturn]
if returnLeft ~= returnRight then
return -iReturn
end
iReturn = iReturn + 1
until returnLeft == nil
return nil
end
local function checkMethodOverrideSignature (signatureBase, signatureOverride, methodType, methodName, errLevel)
local iDiff = compareSignature(signatureBase, signatureOverride)
if iDiff ~= nil then
local what
local iWhat
if iDiff > 0 then
what = "param"
iWhat = iDiff
else
what = "return value"
iWhat = -iDiff
end
error(([[bad %s type #%d to %s '%s' (%s expected, got %s)]])
:format(what, iWhat, methodType, methodName,
formatTypeName(signatureBase[iDiff]),
formatTypeName(signatureOverride[iDiff])),
errLevel+1)
end
end
local forwardDeclaredType = {}
local function createForwardDeclareType (typeName, errorLevel)
if typeName ~= nil then
if type(typeName) ~= "string" then
error("invalid type name (string expected, got " .. type(typeName) .. ")", errorLevel+1)
end
local typeTable = typeNameToTableMap[typeName]
if typeTable ~= nil then
return typeTable
end
end
local typeTable = forwardDeclaredType[typeName]
if typeTable ~= nil then
return typeTable
end
local typeString = (typeName or "anonymousType") .. "(forward declare)"
local typeMeta =
{
magic = ColaPlusTypeTableMagic;
isForwardDeclared = true;
typeName = typeName;
__tostring = function (_)
return typeString
end;
}
typeTable = {}
setmetatable(typeTable, typeMeta)
if typeName ~= nil then
forwardDeclaredType[typeName] = typeTable
end
return typeTable
end
local function isTypeTableForwardDeclared (typeTable)
return getTypeTableMetaNoCheck(typeTable).isForwardDeclared
end
-- if forwardDeclare is given, it's name should equal to typeName
local function createEmptyType (typeName, forwardDeclare, errorLevel)
local resultTable
if forwardDeclare ~= nil then
resultTable = forwardDeclare
else
if typeName == nil then
resultTable = {}
else
resultTable = forwardDeclaredType[typeName] or {}
end
end
if typeName ~= nil then
forwardDeclaredType[typeName] = nil -- fetch the forward declared type table
end
return setmetatable(resultTable, nil)
end
-- check ..., return ...
-- needTypes.selfType = type of self when not static
-- needTypes.format: format(who), needTypes.format: format(i, who)
local function checkValuesCompatible (needTypes, errLevel, ...)
local nGets = select("#", ...)
local nNeeds = #needTypes
local bVarlist = needTypes.bVarlist
if nGets < nNeeds then
local what = needTypes.format:format(needTypes.who)
error(([[too little %s (%d expected, got %d)]])
:format(what, nNeeds, nGets), errLevel+1)
end
if not bVarlist and nGets > nNeeds then
local what = needTypes.format:format(needTypes.who)
error(([[too many %s (%d expected, got %d)]])
:format(what, nNeeds, nGets), errLevel+1)
end
local selfType = needTypes.selfType
if selfType ~= nil then
local self = ...
if self == nil then
local what = needTypes.ithFormat:format(1, needTypes.who)
error(([[bad %s (%s expected, got %s)]])
:format(what, formatTypeName(selfType), formatObjectTypeName(self)), errLevel + 1)
end
end
for i = 1, nNeeds do
local getValue = select(i, ...)
local needType = needTypes[i]
if needType == "varlist" then --"varlist" matches anything
return
end
if not isTypeCompatible(getValue, needType) then
local what = needTypes.ithFormat:format(i, needTypes.who)
error(([[bad %s (%s expected, got %s)]])
:format(what, formatTypeName(needType), formatObjectTypeName(getValue)), errLevel + 1)
end
end
return ...
end
local function createEmptyFunctionWrapper ()
local func
local methodName
local tableType
local bCheckType
local arguments
local returns
return function (...)
local magic, op = ...
if magic == ColaPlusFunctionWrapperControlMagic then -- control command
if op == "set" then
local _, methodInfo
_, _, func, methodName, tableType, methodInfo, bCheckType = ...
local bInstanceMethod =
methodInfo.style:find("s", 1, true) == nil
and methodInfo.style:find("f", 1, true) == nil
local needTypes = methodInfo.valueType
arguments =
{
format="arguments to '%s' in " .. tostring(tableType),
ithFormat="argument #%d to '%s' in " .. tostring(tableType),
who = methodName,
}
returns =
{
format="return values from '%s' in " .. tostring(tableType),
ithFormat="return value #%d from '%s' in " .. tostring(tableType),
who = methodName,
}
do
if bInstanceMethod then
arguments[#arguments + 1] = tableType
arguments.selfType = tableType
end
local iArg = 1
while needTypes[iArg] do
local needType = needTypes[iArg]
if needType == "varlist" then
arguments.bVarlist = true
else
arguments[#arguments + 1] = needType
end
iArg = iArg + 1
end
end
do
local iRet = 1
while needTypes[-iRet] do
local needType = needTypes[-iRet]
if needType == "varlist" then
returns.bVarlist = true
else
returns[iRet] = needTypes[-iRet]
end
iRet = iRet + 1
end
end
end
return
end
-- function call
if bCheckType then
return checkValuesCompatible(returns, 1, func(checkValuesCompatible(arguments, 2, ...)))
else
return func(...)
end
end
end
local function setFunctionWrapper (wrapper, func, methodName, tableType, methodInfo, bCheckType)
wrapper(ColaPlusFunctionWrapperControlMagic, "set", func, methodName, tableType, methodInfo, bCheckType)
end
local function createFunctionWrapper (func, methodName, tableType, methodInfo, bCheckType)
local wrapper = createEmptyFunctionWrapper()
setFunctionWrapper(wrapper, func, methodName, tableType, methodInfo, bCheckType)
return wrapper
end
-- create type with given base type and type name
-- base type could be nil, which means bCreatingClass Object
local function createType (baseTypeTable, typeNameOrForwardDeclare, isInterface)
--
-- checking parameters
--
local theForwardDeclare
local typeName
if type(typeNameOrForwardDeclare) == "table" then
theForwardDeclare = typeNameOrForwardDeclare
local forwardDeclareMeta = getTypeTableMeta(theForwardDeclare)
if forwardDeclareMeta == nil then -- not type table
error("invalid forward declare (type table expected, got " .. type(typeName) .. ")", 2)
end
if not forwardDeclareMeta.isForwardDeclared then
error("invalid forward declare (type is already defined)", 2)
end
if forwardDeclareMeta.typeName ~= nil then
error('invalid forward declare (anonymous expected, got name "' .. forwardDeclareMeta.typeName .. '")', 2)
end
else
typeName = typeNameOrForwardDeclare
--check typeName
if typeName ~= nil then
if type(typeName) ~= "string" then
error("invalid type name (string expected, got " .. type(typeName) .. ")", 2)
end
if typeNameToTableMap[typeName] ~= nil then
error('type with name "' .. typeName .. '" already exist', 2)
end
end
end
--checking base type
if baseTypeTable ~= nil then
local baseMeta = getTypeTableMeta(baseTypeTable)
if baseMeta == nil then
if not bInitializingColaPlus then --when Type extends Object, baseMeta is nil
error ("Param 1 expect a ColaPlus type table, got: " .. type(baseTypeTable), 2)
end
else
if baseMeta.isForwardDeclared then
error("forward declared type " .. tostring(baseTypeTable) .. " can not be inherited", 2)
end
local isBaseInterface = baseMeta.isInterface
if isBaseInterface then -- both explicit interface declaration and extending an interface make the type an interface
isInterface = true
end
if baseTypeTable ~= ColaPlus.Object and isBaseInterface ~= isInterface then
if isInterface then
error("interface can not inherit from non-interface type", 2)
else
error("non-interface can not inherit from interface type", 2)
end
end
end
end
-- set flag that the creation of type has not finished
local bCreatingClass = true
-- the created type
local theType = createEmptyType(typeName, theForwardDeclare, 2)
-- metatable of the type
local typeMeta = {}
--
-- setup typeMeta
--
do
typeMeta.magic = ColaPlusTypeTableMagic
--
-- members
--
-- fields
typeMeta.fields = {}
-- constructors
typeMeta.constructors = {}
-- non-static methods
typeMeta.abstractMethods = {}
-- abstract non-static methods
typeMeta.methods = {}
-- static methods, static and constant fields
typeMeta.staticMembers = {}
-- members info map (for checking)
if feature_member_info then
typeMeta.memberInfoMap = {}
end
--
-- extra information
--
typeMeta.isInterface = isInterface
typeMeta.baseTypeTable = baseTypeTable
typeMeta.typeName = typeName
local typeString = (typeName or "anonymousType") .. "(" .. tostring(theType) .. ")"
typeMeta.__tostring = function (_)
return typeString
end
-- build type info (for convertion)
typeMeta.typeInfo = nil --will be created when call obj:getType()
typeMeta.compatibleTypes = { [theType] = true } -- base type will be add by inheritMembers()
typeMeta.implementInterfaces = {} -- only directly implemented interfaces
end
-- inherit from baseTypeTable
if baseTypeTable ~= nil then
inheritMembers(typeMeta, baseTypeTable)
end
--
-- Add interface
--
--[[
Special operator Implement
declare that this type implements an interface
param interfaceTypeTable: type table of interface
return type table itself
e.g: MyClass.Implement(IEquatable).Implement(IComparable)
]]
function theType.Implement (interfaceTypeTable)
typeMeta.compatibleTypes[interfaceTypeTable] = true
typeMeta.implementInterfaces[interfaceTypeTable] = true
return theType
end
--
-- member declare
--
-- style is a string, each char stands for a flag
-- 'c': constant
local function FieldInternal (style, fieldType)
if isInterface then
error("interface can not have field", 2)
end
if not bCreatingClass then
error("bad field defining (type " .. tostring(theType) .. " is already committed)", 2)
end
local bConstant = (style == "c")
return createProxy
{
__index = function (_, fieldName)
error("You need to give field a default value", 2)
end;
__newindex = function (_, fieldName, initValue)
if type(fieldName) ~= "string" then
error("Field name should be string, got: "..type(fieldName), 2)
end
local memberInfo
if feature_member_info then
local memberInfoMap = typeMeta.memberInfoMap
-- checking name conflict
if memberInfoMap[fieldName] ~= nil then
error('member with name "' .. fieldName .. '" already exists', 2)
end
checkValidArgType(fieldType, 1, fieldName, 2)
-- record member info
memberInfo =
{
memberType = "field",
style = style,
typeTable = theType,
inheritable = true,
valueType = fieldType
}
end
if bConstant then
checkValueCompatible(initValue, fieldType, [[initial value to field '%s']], fieldName, 2)
typeMeta.staticMembers[fieldName] = initValue
else
local initValueType = type(initValue)
if not primaryTypeSet[initValueType] and initValueType ~= "function" then
initValueError(fieldName, "number, boolean, string, nil or function", initValueType, 2)
end
if type(initValue) ~= "function" then
checkValueCompatible(initValue, fieldType, [[initial value to field '%s']], fieldName, 2)
end
typeMeta.fields[fieldName] = initValue --... checking whether table, userdata
end
-- register member info only when succeeded
if feature_member_info then
local memberInfoMap = typeMeta.memberInfoMap
memberInfoMap[fieldName] = memberInfo
end
end;
}
end
--[[
Special operator Field
Declare a field
Initial value of the field can only be number, boolean, string, nil or function
If initial value is a function, it will be called when instantiate object. The return value will be assigned to field
param fieldType: type of field
e.g:
Field("number").m_fieldName_1 = 1
Field("table").m_fieldName_2 = function () return {"new table"} end
]]
local function Field (fieldType)
return FieldInternal("", fieldType)
end
--[[
Special operator ConstField
declare a static field
param fieldType: type of field
e.g: Field("number").m_fieldName = 1
]]
local function ConstField (fieldType)
return FieldInternal("c", fieldType)
end
-- style is a string, each char stands for a flag
-- 's': static, 'v': virtual, 'o': override, 'f': final
local function MethodInternal (style, ...)
if not bCreatingClass then
error("bad method defining (type " .. tostring(theType) .. " is already committed)", 2)
end
assert(#style <= 1)
local bStatic = (style == "s")
local bVirtual = (style == "v")
local bOverride = (style == "o")
local bFinal = (style == "f")
local bConstructor = (style == "c")
local paramCount
local paramList
if feature_member_info then
paramCount = select("#", ...)
paramList = {...}
end
return createProxy
{
__index = function (_, methodName)
error("You need to give method a function body", 2)
end;
__newindex = function (_, methodName, functionBody)
if type(methodName) ~= "string" then
error("Method name should be string, got: "..type(methodName), 2)
end
if type(functionBody) ~= "function" then
error("Need function body, got: "..type(functionBody), 2)
end
if feature_member_info then
local memberInfoMap = typeMeta.memberInfoMap
local baseMemberInfo
-- checking name conflict
if not bConstructor and memberInfoMap[methodName] ~= nil then
local oldInfo = memberInfoMap[methodName]
if bOverride and oldInfo.memberType == "method" --only "override" method can override others
and oldInfo.typeTable ~= theType then --can only override once in one type
if oldInfo.style == "v" or oldInfo.style == "o" then
baseMemberInfo = oldInfo -- will check signature later
else
error('Can not override non-virtual method "' .. methodName .. '"', 2)
end
else
error('member with name "' .. methodName .. '" already exists', 2)
end
end
-- checking constructor
if bConstructor and paramCount ~= 0 then
error([[constructor can not have extra param and return value]], 2)
end
-- checking override
if bOverride and baseMemberInfo == nil then
error('overrided method with name "' .. methodName .. '" not exists', 2)
end
local memberInfo =
{
memberType = "method",
style = style,
typeTable = theType,
inheritable = not bFinal,
valueType = checkMethodParamAndMakeList(paramCount, paramList, methodName, 2)
}
-- record member info
if not bConstructor then
if baseMemberInfo ~= nil then
checkMethodOverrideSignature(baseMemberInfo.valueType, memberInfo.valueType, "override method", methodName, 2)
end
memberInfoMap[methodName] = memberInfo
end
if feature_calling_checking then
functionBody = createFunctionWrapper(functionBody, methodName, theType, memberInfo, true)
end
end
if bConstructor then
if isInterface then
error("Interface can not have constructor", 2)
end
typeMeta.constructors[#typeMeta.constructors+1] = functionBody
elseif bStatic or bFinal then
if isInterface then
error("Interface can not have static method", 2)
end
typeMeta.staticMembers[methodName] = functionBody
else
if isInterface then
typeMeta.abstractMethods[methodName] = functionBody
else
typeMeta.methods[methodName] = functionBody
end
end
end;
}
end
--[[
Special operation Method
declare a method
params: params types and return value types, params types and return types are seperated by "=>"
e.g:
-- declare method with one number param and no return value
Method("number").foo = function (self, numberParam) end
-- declare method with one number param, one string param, one boolean return value, and one string return value
Method("number", "string", "=>", "boolean", "string").foo = function (self, numberParam) end
]]
local function Method (...)
return MethodInternal("", ...)
end
--[[
Special operation VirtualMethod
declare a virtual method
a virtual method is similar to normal method, but can be overrided
]]
local function VirtualMethod (...)
return MethodInternal("v", ...)
end
--[[
Special operation OverrideMethod
declare a override method
Virtual method of base type can be overrided
]]
local function OverrideMethod (...)
return MethodInternal("o", ...)
end
--[[
Special operation StaticMethod
declare a static method
params: params types and return value types, params types and return types are seperated by "=>"