-
Notifications
You must be signed in to change notification settings - Fork 5
/
pLuaObject.pas
1529 lines (1296 loc) · 44.7 KB
/
pLuaObject.pas
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
unit pLuaObject;
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$TYPEDADDRESS ON}
{$ENDIF}
{$I pLua.inc}
interface
uses
Classes, SysUtils, fgl,
lua, pLua, uWordList;
type
TLuaObjectEventDelegate = class;
PLuaInstanceInfo = ^TLuaInstanceInfo;
PPLuaInstanceInfo = ^PLuaInstanceInfo;
plua_ClassMethodWrapper = function(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
plua_PropertyReader = plua_ClassMethodWrapper;
plua_PropertyWriter = plua_ClassMethodWrapper;
plua_MethodWrapper = plua_ClassMethodWrapper;
plua_ClassConstructor = function(l : Plua_State; paramidxstart, paramcount : integer; InstanceInfo : PLuaInstanceInfo) : TObject;
plua_ClassDestructor = procedure(target : TObject; l : Plua_State);
PLuaClassInfo = ^TLuaClassInfo;
PLuaClassProperty = ^TLuaClassProperty;
TLuaClassProperty = record
PropName : AnsiString;
Reader : plua_PropertyReader;
Writer : plua_PropertyWriter;
end;
TLuaClassMethod = record
MethodName : AnsiString;
wrapper : plua_MethodWrapper;
end;
TLuaClassId = type Pointer; //just a pointer is enough to identify "class-ness"
TLuaClassInfo = record
ClassId : TLuaClassId;
Parent : PLuaClassInfo;
ClassName : AnsiString;
New : plua_ClassConstructor;
Release : plua_ClassDestructor;
PropHandlers: TWordList;
UnhandledReader : plua_PropertyReader;
UnhandledWriter : plua_PropertyWriter;
Properties : Array of TLuaClassProperty;
Methods : Array of TLuaClassMethod;
// information for representing special kinds of objects behaving a lot like Lua tables
// they will support following operations
// - read value by key
// - insert key/value (first assignment of non-existing key)
// - modify value by key (ordinary assignment)
// - remove item by key (via nil assignment)
// - iterate all key/values (via __pairs metamethod support)
OnRead : plua_ClassMethodWrapper; // receives the same arguments as __index metamethod
OnReadByIndex : plua_ClassMethodWrapper; // receives single integer argument in [0..KeyCount-1] range, returns key/value pair
OnInsertModifyRemove : plua_ClassMethodWrapper; // receives the same arguments as __newindex metamethod
OnGetKeyCount : plua_ClassMethodWrapper; // will return key count to initialize iteration via "for in" loop
end;
TLuaInstanceInfo = record
OwnsObject: Boolean;
LuaRef : Integer;
ClassId : TLuaClassId;
l : PLua_state;
obj : TObject;
Delegate : TLuaObjectEventDelegate;
{$IFDEF DEBUG}
//in case some leakage/double freeing occurs, we'll know what class did that.
ClassName:string;
{$ENDIF}
end;
TClassIdObjMap = specialize TFPGMap<TLuaClassId, PLuaClassInfo>;
{ TLuaClassList }
TLuaClassList = class
fItems : TList;
//just an index to get PLuaClassInfo by ClassId quickly
FClassIdToClassInfo:TClassIdObjMap;
private
function GetClassInfo(index : integer): PLuaClassInfo;
function GetClassInfoById(Id : TLuaClassId): PLuaClassInfo;
function GetCount: integer;
procedure FreeItem(ci: PLuaClassInfo);
public
constructor Create;
destructor Destroy; override;
function GetPropReader( ClassId : TLuaClassId; const aPropertyName : AnsiString ) : plua_PropertyReader;
function GetPropWriter( ClassId : TLuaClassId; const aPropertyName : AnsiString; out ReadOnly : Boolean ) : plua_PropertyWriter;
function GetInfo(l : Plua_State; InstanceObject : TObject) : PLuaInstanceInfo;
//AHTUNG!!! Do not try to use aClassInfo after Add!!!
function Add(aClassInfo : PLuaClassInfo) : Integer;
procedure Remove(aClassName : AnsiString);
function IndexOf(aClassName : AnsiString) : Integer;
procedure Clear;
property Count : integer read GetCount;
property ClassInfo[index : integer]:PLuaClassInfo read GetClassInfo; default;
property ClassInfoById[Id : TLuaClassId]:PLuaClassInfo read GetClassInfoById;
end;
{ TLuaObjectEventDelegate }
TLuaObjectEventDelegate = class
protected
FInstanceInfo : PLuaInstanceInfo;
FObj : TObject;
FLua : {TLuaInternalState} Pointer;
function EventExists( EventName :AnsiString ) : Boolean;
function CallEvent( EventName :AnsiString ) : Integer; overload;
function CallEvent( EventName :AnsiString;
const Args: array of Variant ) : Integer; overload;
function CallEvent( EventName :AnsiString;
const Args: array of Variant;
Results : PVariantArray = nil):Integer; overload;
public
constructor Create( Lua: {TLuaInternalState} Pointer; InstanceInfo : PLuaInstanceInfo; obj : TObject); virtual;
destructor Destroy; override;
end;
{ TLuaClassTypesList }
TLuaClassTypesList = class
fItems : TWordList;
fItemList : TList;
private
function GetCount: Integer;
function GetIndexedItem(index : integer): PLuaClassInfo;
function GetItem(ItemName : AnsiString): PLuaClassInfo;
public
constructor Create;
destructor Destroy; override;
function Add(ItemName : AnsiString; LuaParent : PLuaClassInfo = nil) : PLuaClassInfo;
procedure Remove(ItemName : AnsiString);
procedure Clear;
procedure RegisterTo(L : PLua_State);
property Item[ItemName : AnsiString] : PLuaClassInfo read GetItem; default;
property IndexedItem[index : integer] : PLuaClassInfo read GetIndexedItem;
property Count : Integer read GetCount;
end;
procedure plua_registerclass( l : PLua_State; classInfo : PLuaClassInfo);
procedure plua_newClassInfo( var ClassInfoPointer : PLuaClassInfo);
procedure plua_initClassInfo( var ClassInfo : TLuaClassInfo);
procedure plua_releaseClassInfo( var ClassInfoPointer : PLuaClassInfo);
procedure plua_AddClassProperty( var ClassInfo : TLuaClassInfo;
propertyName : AnsiString;
Reader : plua_PropertyReader;
Writer : plua_PropertyWriter = nil // properties can be read-only
);
procedure plua_AddClassMethod( var ClassInfo : TLuaClassInfo;
methodName : AnsiString;
wrapper : plua_MethodWrapper );
function plua_getObject( l : PLua_State; idx : Integer; PopValue:boolean = True) : TObject;
function plua_GlobalObjectGet( l : PLua_State; const varName:string) : TObject;
function plua_getObjectTable( l : PLua_State; idx : Integer; PopValue:boolean = True) : TObjArray;
function plua_getObjectInfo( l : PLua_State; idx : Integer) : PLuaInstanceInfo;
function plua_registerExisting( l : PLua_State; InstanceName : AnsiString;
ObjectInstance : TObject;
classId : TLuaClassId;
FreeOnGC : Boolean = false; KeepRef:boolean = True) : PLuaInstanceInfo;
//Function pushes an object into stack.
function plua_pushexisting( l : PLua_State;
ObjectInstance : TObject;
classId : TLuaClassId;
FreeOnGC : Boolean = false; //Call native destructor on garbage collecting?
KeepRef:boolean = True //Reference keeps garbage collector from freeing object, until application decides to release it.
//If KeepRef is true, then application itself is responsible for freeing Lua object using pLua_ObjectMarkFree
) : PLuaInstanceInfo;
//special object registering
//e.g. Self for LuaWrapper.
//Does not adds objects into internal lists, as they don't exist yet.
//Chicken/egg problem avoidance.
function plua_pushexisting_special( l : PLua_State;
ObjectInstance : TObject;
classId: TLuaClassId; //Important!!! Can be nil here!
FreeOnGC : Boolean = false; //Call native destructor on garbage collecting?
KeepRef:boolean = True //Reference keeps garbage collector from freeing object, until application decides to release it.
//If KeepRef is true, then application itself is responsible for freeing Lua object using pLua_ObjectMarkFree
) : PLuaInstanceInfo;
//Pushes class object as opaque userdata. Useful e.g. for iterators which are pushed by Pascal as userdata+finalizer
//automatically calls Free on garbage collection
procedure plua_PushObjectAsUserData(l: Plua_State; O:TObject);
// only for freeing instances made by plua_pushexisting_special!
procedure plua_instance_free(l: Plua_State; var Instance: PLuaInstanceInfo);
function plua_ObjectMarkFree(l: Plua_State; ObjectInstance: TObject):boolean;
function plua_ref_release(l : PLua_State; obj:PLuaInstanceInfo):boolean;overload;
function plua_PushObject(ObjectInfo : PLuaInstanceInfo) : Boolean;
function plua_GetObjectInfo(l : Plua_State; InstanceObject : TObject) : PLuaInstanceInfo;
function plua_ObjectEventExists( ObjectInfo : PLuaInstanceInfo;
EventName :AnsiString ) : Boolean;
function plua_CallObjectEvent( ObjectInfo : PLuaInstanceInfo;
EventName :AnsiString;
const Args: array of Variant;
Results : PVariantArray = nil):Integer;
function plua_AllocatedObjCount(L : PLua_State):Integer;
implementation
uses
typinfo, LuaWrapper;
function plua_GetEventDeletage(S: TLuaInternalState; Obj : TObject ) : TLuaObjectEventDelegate;forward;
function ClassMetaTableName(const ClassName:string):string;
begin
Result:=ClassName+'_mt';
end;
function ClassMetaTableName(cinfo:PLuaClassInfo):string;
begin
Result:=ClassMetaTableName(cinfo^.ClassName);
end;
function ClassProcsMetaTableName(const ClassName:string):string;
begin
//Return metatable name for class methods metatable
Result:=ClassName+'_mt_procs';
end;
function ClassProcsMetaTableName(cinfo:PLuaClassInfo):string;
begin
//Return metatable name for class methods metatable
Result:=ClassProcsMetaTableName(cinfo^.ClassName);
end;
function ClassPropsMetaTableName(const ClassName:string):string;
begin
//Return metatable name for class properties metatable
Result:=ClassName+'_mt_props';
end;
function ClassPropsMetaTableName(cinfo:PLuaClassInfo):string;
begin
//Return metatable name for class properties metatable
Result:=ClassPropsMetaTableName(cinfo^.ClassName);
end;
function plua_ref_release(l : PLua_State; obj_ref:Integer):boolean;overload;
begin
Result:=obj_ref <> LUA_NOREF;
if Result then
begin
luaL_unref(L, LUA_REGISTRYINDEX, obj_ref);
end;
end;
function plua_ref_release(l : PLua_State; obj:PLuaInstanceInfo):boolean;overload;
begin
Result:=plua_ref_release(l, obj^.LuaRef);
obj^.LuaRef:=LUA_NOREF;
end;
function plua_instance_new: PLuaInstanceInfo;
begin
New(Result);
FillChar(Result^, Sizeof(Result^), 0);
Result^.LuaRef:=LUA_NOREF;
end;
function plua_AllocatedObjCount(l : Plua_State):Integer;
var S:TLuaInternalState;
begin
S:=LuaSelf(l);
Result:=S.LuaObjects.Count;
end;
function plua_gc_class(l : PLua_State) : integer; extdecl; forward;
function plua_index_class(l : PLua_State) : integer; extdecl;
var
propName : AnsiString;
propValueStart : Integer;
obj : TObject;
cInfo : PLuaInstanceInfo;
reader : plua_PropertyReader;
v : variant;
pcount : Integer;
begin
result := 0;
pcount := lua_gettop(l);
cInfo := plua_getObjectInfo(l, 1);
if not assigned(cInfo) then
exit;
obj := cInfo^.obj;
propName := plua_tostring(l, 2);
propValueStart := 3;
//remove parameters from stack
lua_pop(l, 2);
reader := LuaSelf(l).LuaClasses.GetPropReader(cInfo^.ClassId, propName);
if assigned(reader) then
result := reader(obj, l, propValueStart, pcount)
else
begin
if IsPublishedProp(obj, propName) then
begin
try
v := GetPropValue(obj, propName);
plua_pushvariant(l, v);
result := 1;
except
end;
end;
end;
end;
function plua_newindex_class(l : PLua_State) : integer; extdecl;
var
propName : AnsiString;
propValueStart : Integer;
obj : TObject;
cInfo : PLuaInstanceInfo;
writer : plua_PropertyReader;
bReadOnly: Boolean;
pcount : Integer;
begin
result := 0;
pcount := lua_gettop(l);
cinfo := plua_getObjectInfo(l, 1);
if not assigned(cInfo) then
exit;
obj := cInfo^.obj;
propName := plua_tostring(l, 2);
propValueStart := 3;
writer := LuaSelf(l).LuaClasses.GetPropWriter(cInfo^.ClassId, propName, bReadOnly);
if assigned(writer) then
result := writer(obj, l, propValueStart, pcount)
else
begin
if not bReadOnly then
begin
plua_pushstring(l, propName);
lua_pushvalue(l, propValueStart);
lua_rawset(l, 1);
end;
end;
//remove parameters from stack
lua_pop(l, 2);
end;
function plua_call_class_method_act(l : PLua_State) : integer;
var
method : plua_MethodWrapper;
obj : TObject;
pcount : Integer;
begin
result := 0;
pcount := lua_gettop(l);
obj := plua_getObject(l, 1, False);
method := plua_MethodWrapper(lua_topointer(l, lua_upvalueindex(1)));
if assigned(obj) and assigned(method) then
result := method(obj, l, 2, pcount);
end;
// exception support
const pLuaExceptActual:TLuaNakedProc = @plua_call_class_method_act;
{$I pLuaExceptWrapper.inc}
function plua_new_class(l : PLua_State) : integer; extdecl;
var
i, n, tidx, midx, oidx : Integer;
classId : TLuaClassId;
cInfo : PLuaClassInfo;
instance: PLuaInstanceInfo;
pcount : integer;
obj_user: PPLuaInstanceInfo;
begin
pcount := lua_gettop(l);
result := 0;
n := lua_gettop(l);
if (n < 1) or (not (lua_istable(l, 1))) then
exit;
tidx := 1;
lua_pushstring(l, '__ClassId');
lua_rawget(l, tidx);
classId := lua_topointer(l, -1);
lua_pop(l, 1);
if classId = nil then Exit;
cInfo := LuaSelf(l).LuaClasses.ClassInfoById[ classId ];
instance:=plua_instance_new;
instance^.OwnsObject := true;
instance^.ClassId := classId;
instance^.l := l;
if cInfo^.New <> nil then
instance^.obj := cInfo^.New(l, 2, pcount, instance)
else
instance^.obj := TObject.Create;
LuaObjects_Add( LuaSelf(l), instance );
instance^.LuaRef := luaL_ref(L, LUA_REGISTRYINDEX);
obj_user:=lua_newuserdata(L, sizeof(instance));
obj_user^:=instance;
lua_getglobal(l, PChar(ClassMetaTableName(cinfo)) );
lua_setmetatable(l, -2);
result := 1;
end;
function plua_gc_class(l : PLua_State) : integer; extdecl;
var
nfo : PLuaInstanceInfo;
d : TLuaObjectEventDelegate;
ref : Integer;
begin
result := 0;
nfo := plua_getObjectInfo(l, 1);
if not assigned(nfo) then
exit;
d := plua_GetEventDeletage(LuaSelf(l), nfo^.obj);
if assigned(d) then
d.Free;
//to avoid double release,
//first release object and only after release reference
//ref:=nfo^.LuaRef;
LuaObjects_Free( LuaSelf(l), nfo);
//plua_ref_release(l, ref);
end;
procedure plua_pushmethod(l: PLua_State; const MethodName:string; wrapper:plua_ClassMethodWrapper);
//pushes wrapper method on Lua stack
begin
plua_pushstring(L, MethodName);
lua_pushlightuserdata(l, Pointer(wrapper));
lua_pushcclosure(L, @plua_call_method, 1);
end;
procedure plua_pushmethod(l: PLua_State; wrapper:plua_ClassMethodWrapper);
//pushes wrapper method on Lua stack
begin
lua_pushlightuserdata(l, Pointer(wrapper));
lua_pushcclosure(L, @plua_call_method, 1);
end;
type
TRegisterClassInfo = record
ClassMetaTable : string;
ProcsMetaTable : string;
PropsMetaTable : string;
end;
function plua_registerclass_createmt(l: PLua_State; const ClassName: string; ClassId : TLuaClassId; out R:TRegisterClassInfo):boolean;
// Creates metatable for given class info
var
S:TLuaInternalState;
begin
Result:=False;
//already registered?
R.ClassMetaTable:=ClassMetaTableName(ClassName);
lua_getglobal( l, PChar(R.ClassMetaTable) );
if lua_istable(l, -1) then
begin
LogDebug('Skipping registering class %s. Metatable already registered', [ClassName]);
Exit;
end;
lua_pop(l, 1);
S:=LuaSelf(l);
//skip re-registering classes.
if S.LuaClasses.IndexOf( ClassName ) <> -1 then
begin
LogDebug('Skipping registering class %s. Already registered', [ClassName]);
Exit;
end;
plua_pushstring(l, ClassName);
lua_newtable(l);
//assign internal class id to class table
lua_pushstring(L, '__ClassId');
lua_pushlightuserdata(L, ClassId);
lua_rawset(L, -3);
//assign named metatable to class table
pLua_TableGlobalCreate(l, R.ClassMetaTable);
lua_getglobal(l, PChar(R.ClassMetaTable) );
lua_setmetatable(l, -2);
// create named class table
lua_settable(l, LUA_GLOBALSINDEX);
R.ProcsMetaTable:=ClassProcsMetaTableName(ClassName);
R.PropsMetaTable:=ClassPropsMetaTableName(ClassName);
Result:=True;
end;
function plua_ObjInstance(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
// return object instance pointer for using e.g. in FFI calls
begin
lua_pop(l, 1); // remove self pointer from stack
lua_pushlightuserdata(L, Pointer(target));
Result:=1;
end;
procedure plua_registerclass(l: PLua_State; classInfo: PLuaClassInfo);
{$REGION 'STDCLASS'}
procedure CreateProps(const R:TRegisterClassInfo);
var midx : integer;
begin
//create properties metatable
pLua_TableGlobalCreate(l, R.PropsMetaTable);
//attach property read/write handlers to properties metatable
lua_getglobal(l, PChar(R.PropsMetaTable) );
midx := lua_gettop(l);
lua_pushstring(L, 'getprop');
lua_pushcfunction(L, @plua_index_class);
lua_rawset(L, midx);
lua_pushstring(L, 'setprop');
lua_pushcfunction(L, @plua_newindex_class);
lua_rawset(L, midx);
lua_pop(l, 1);
end;
procedure CreateMethods(const R:TRegisterClassInfo);
const
ObjInstanceMethod = 'ObjInstance';
var midx, i: integer;
begin
//create methods metatable
pLua_TableGlobalCreate(l, R.ProcsMetaTable);
//attach properties metatable to methods metatable
//so properties metatable is searched only when no methods is found
lua_getglobal(l, PChar(R.ProcsMetaTable) );
midx := lua_gettop(l);
//populate class methods metatable
LogDebug('Registering class methods.');
//register special function ObjInstance to return real FPC object instance pointer
//it can be passed via FFI to speed up any method calls
plua_pushmethod(L, ObjInstanceMethod, @plua_ObjInstance);
lua_rawset(l, midx);
if Length(classInfo^.Methods) > 0 then
begin
// TODO - Add parent method calls in
for i := 0 to High(classInfo^.Methods) do
begin
LogDebug('Registering class method %s.', [classInfo^.Methods[i].MethodName]);
with classInfo^.Methods[i] do
plua_pushmethod(L, MethodName, wrapper);
lua_rawset(l, midx);
end;
end;
LogDebug('Registering class methods - done.');
lua_pop(l, 1);
end;
procedure CreateStdMetaMethods(const R:TRegisterClassInfo);
var midx: integer;
begin
//populate main class metatable
lua_getglobal(l, PChar(R.ClassMetaTable) );
midx := lua_gettop(l);
lua_pushstring(L, '__call');
lua_pushcfunction(L, @plua_new_class);
lua_rawset(L, midx);
lua_pushstring(L, '__gc');
lua_pushcfunction(L, @plua_gc_class);
lua_rawset(L, midx);
//pop class metatable
lua_pop(l, 1);
end;
procedure CreateStdMethodPropSupport(const R:TRegisterClassInfo);
var midx, err : integer;
begin
//populate main class metatable
lua_getglobal(l, PChar(R.ClassMetaTable) );
midx := lua_gettop(l);
lua_pushstring(L, '__index');
err:=plua_FunctionCompile(l,
'function(v,x) ' + sLineBreak +
' if (%mt_procs%[x] ~= nil) then ' + sLineBreak +
' return %mt_procs%[x] ' + sLineBreak +
' else ' + sLineBreak +
' return (%mt_props%.getprop)(v, x) ' + sLineBreak +
' end ' + sLineBreak +
'end',
['%mt_procs%', R.ProcsMetaTable,
'%mt_props%', R.PropsMetaTable]);
if err <> 0 then
begin
plua_RaiseException(l, 'Cannot compile __index function for class %s metatable', [classInfo^.ClassName]);
end;
lua_rawset(L, midx);
lua_pushstring(L, '__newindex');
err:=plua_FunctionCompile(l,
'function(t,p,val) ' + sLineBreak +
' %mt_props%.setprop(t, p, val) ' + sLineBreak +
'end',
['%mt_props%', R.PropsMetaTable]);
if err <> 0 then
begin
plua_RaiseException(l, 'Cannot compile __newindex function for class %s metatable', [classInfo^.ClassName]);
end;
lua_rawset(L, midx);
//pop class metatable
lua_pop(l, 1);
end;
procedure CreateStdClass(const R:TRegisterClassInfo);
begin
//Pseudo-code for metatables created below
// So, I just make a chain of metatables!
//
// class_mt_props = {
// getprop = plua_index_class,
// setprop = plua_newindex_class
// }
//
// class_mt_procs = {
// proc1 = plua_call_class_method,
// proc2 = plua_call_class_method
// ...
// }
//
// class_mt = {
// __gc = plua_gc_class,
// __call = plua_new_class
// __index= function(v,x)
// if (mt_procs[x] ~= nil) then
// return mt_procs[x]
// else
// return (mt_props.getprop)(v, x)
// end
// end,
// __newindex= function(t,p,val)
// mt_props.setprop(t, p, val)
// end
// }
// setmetatable(obj, class_mt)
//create properties metatable
CreateProps(R);
//create methods metatable
CreateMethods(R);
CreateStdMetaMethods(R);
CreateStdMethodPropSupport(R);
end;
{$ENDREGION}
{$REGION 'TABLECLASS'}
procedure CreateTableMetaSupport(const R:TRegisterClassInfo);
var midx, err : integer;
begin
//populate main class metatable
lua_getglobal(l, PChar(R.ClassMetaTable) );
midx := lua_gettop(l);
lua_pushstring(L, 'OnRead');
plua_pushmethod(l, classInfo^.OnRead);
lua_rawset(L, midx);
lua_pushstring(L, '__index');
err:=plua_FunctionCompile(l,
'function(t,k)' +sLineBreak+
' local mt = getmetatable(t)' +sLineBreak+
' if mt.OnReadWrapper == nil then' +sLineBreak+
' return mt.OnRead(t,k)' +sLineBreak+
' else' +sLineBreak+
' return mt.OnReadWrapper( mt.OnRead, t, k )' +sLineBreak+
' end' +sLineBreak+
'end');
if err <> 0 then
plua_RaiseException(l, 'Cannot compile __index function for class %s metatable', [classInfo^.ClassName]);
lua_rawset(L, midx);
lua_pushstring(L, 'OnInsertModifyRemove');
plua_pushmethod(l, classInfo^.OnInsertModifyRemove);
lua_rawset(L, midx);
lua_pushstring(L, '__newindex');
err:=plua_FunctionCompile(l,
'function(t,k,v)' +sLineBreak+
' local mt = getmetatable(t)' +sLineBreak+
' if mt.OnInsertModifyRemoveWrapper == nil then' +sLineBreak+
' mt.OnInsertModifyRemove(t,k,v)' +sLineBreak+
' else' +sLineBreak+
' mt.OnInsertModifyRemoveWrapper( mt.OnInsertModifyRemove, t, k, v )' +sLineBreak+
' end' +sLineBreak+
'end');
if err <> 0 then
plua_RaiseException(l, 'Cannot compile __newindex function for class %s metatable', [classInfo^.ClassName]);
lua_rawset(L, midx);
lua_pushstring(L, '__len');
plua_pushmethod(l, classInfo^.OnGetKeyCount);
lua_rawset(L, midx);
// publish OnReadByIndex for __pairs function
lua_pushstring(L, 'OnReadByIndex');
plua_pushmethod(l, classInfo^.OnReadByIndex);
lua_rawset(L, midx);
// publish OnGetKeyCount for __pairs function
lua_pushstring(L, 'OnGetKeyCount');
plua_pushmethod(l, classInfo^.OnGetKeyCount);
lua_rawset(L, midx);
lua_pushstring(L, '__pairs');
err:=plua_FunctionCompile(l,
'function(t)' +sLineBreak+
' local i = -1' +sLineBreak+
' local mt = getmetatable(t)' +sLineBreak+
// additional checks
' if (mt == nil) or ' +sLineBreak+
' (mt.OnGetKeyCount == nil) or' +sLineBreak+
' (mt.OnReadByIndex == nil) then' +sLineBreak+
' return function()' +sLineBreak+
' return nil, nil' +sLineBreak+
' end, t, nil' +sLineBreak+
' end' +sLineBreak+
' local count = mt.OnGetKeyCount(t)' +sLineBreak+
' return function()' +sLineBreak+
' if (count == nil) or (i >= count-1) then' +sLineBreak+
' return nil, nil' +sLineBreak+
' end' +sLineBreak+
' i = i + 1' +sLineBreak+
' if mt.OnReadByIndexWrapper == nil then' +sLineBreak+
' return mt.OnReadByIndex(t,i)' +sLineBreak+
' else' +sLineBreak+
' return mt.OnReadByIndexWrapper( mt.OnReadByIndex, t, i )' +sLineBreak+
' end' +sLineBreak+
' end, t, nil' +sLineBreak+
'end');
if err <> 0 then
plua_RaiseException(l, 'Cannot compile __pairs function for class %s metatable', [classInfo^.ClassName]);
lua_rawset(L, midx);
//pop class metatable
lua_pop(l, 1);
end;
procedure CreateTableClass(const R:TRegisterClassInfo);
begin
//Pseudo-code for metatable created below
//
// class_mt = {
// __gc = plua_gc_class,
// __call = plua_new_class,
// __index= function(t,x)
// return OnRead(t, x)
// end,
// __newindex= function(t,p,val)
// OnInsertModifyRemove(t,p,val)
// end,
// __len= function(t)
// return OnGetKeyCount(t)
// end,
// OnReadByIndex = function(t,i)
// return OnReadByIndex(t,i)
// end,
// __pairs= function(t)
// local i = -1
// local mt = getmetatable(t)
// local count = mt.OnGetKeyCount(t)
// return function()
// if i >= count-1 then
// return
// end
// i = i + 1
// return i, mt.OnReadByIndex(t,i)
// end
// end
// }
// setmetatable(obj, class_mt)
with classInfo^ do
Assert( (OnRead <> nil) and
(OnReadByIndex <> nil) and
(OnInsertModifyRemove <> nil) and
(OnGetKeyCount <> nil),
'All class as table meta info must be filled'
);
CreateStdMetaMethods(R);
CreateTableMetaSupport(R);
end;
{$ENDREGION}
var StartTop: integer;
R:TRegisterClassInfo;
S:TLuaInternalState;
begin
LogDebug('Registering class %s.', [classInfo^.ClassName]);
StartTop := lua_gettop(l);
if not plua_registerclass_createmt(l, classInfo^.ClassName, classInfo^.ClassId, R) then
begin
plua_EnsureStackBalance(l, StartTop);
plua_releaseClassInfo(classInfo); // release class info as reference wasn't added to LuaClasses
LogDebug('Registering - skipped, already exists.');
Exit;
end;
S:=LuaSelf(l);
S.LuaClasses.Add(classInfo); // now LuaClasses become the owner of classInfo
if classInfo^.OnInsertModifyRemove = nil then
CreateStdClass(R)
else
CreateTableClass(R);
plua_CheckStackBalance(l, StartTop);
LogDebug('Registering - done.');
end;
procedure plua_newClassInfo(var ClassInfoPointer: PLuaClassInfo);
begin
new(ClassInfoPointer);
plua_initClassInfo(ClassInfoPointer^);
end;
procedure plua_initClassInfo( var ClassInfo: TLuaClassInfo);
begin
ClassInfo.ClassName := '';
ClassInfo.Parent := nil;
ClassInfo.New := nil;
ClassInfo.Release := nil;
ClassInfo.PropHandlers := TWordList.Create;
ClassInfo.UnhandledReader := nil;
ClassInfo.UnhandledWriter := nil;
SetLength(ClassInfo.Properties, 0);
SetLength(ClassInfo.Methods, 0);
ClassInfo.OnRead := nil;
ClassInfo.OnReadByIndex := nil;
ClassInfo.OnInsertModifyRemove := nil;
ClassInfo.OnGetKeyCount := nil;
end;
procedure plua_releaseClassInfo(var ClassInfoPointer: PLuaClassInfo);
begin
Finalize(ClassInfoPointer^.Properties);
Finalize(ClassInfoPointer^.Methods);
ClassInfoPointer^.PropHandlers.Free;
ClassInfoPointer^.PropHandlers:=nil;
Freemem(ClassInfoPointer);
ClassInfoPointer:=nil;
end;
procedure plua_AddClassProperty(var ClassInfo: TLuaClassInfo;
propertyName: AnsiString; Reader: plua_PropertyReader;
Writer: plua_PropertyWriter);
var
idx : integer;
begin
idx := Length(ClassInfo.Properties);
SetLength(ClassInfo.Properties, idx+1);
ClassInfo.Properties[idx].PropName := propertyName;
ClassInfo.Properties[idx].Reader := Reader;
ClassInfo.Properties[idx].Writer := Writer;
ClassInfo.PropHandlers.AddWord(propertyName)^.data := pointer(PtrUint(idx));
end;
procedure plua_AddClassMethod(var ClassInfo: TLuaClassInfo;
methodName: AnsiString; wrapper: plua_MethodWrapper);
var
idx : integer;
begin
idx := Length(ClassInfo.Methods);
SetLength(ClassInfo.Methods, idx+1);
ClassInfo.Methods[idx].MethodName := methodName;
ClassInfo.Methods[idx].wrapper := wrapper;
end;
function plua_getObject(l: PLua_State; idx: Integer; PopValue:boolean): TObject;
var
obj_user:PPLuaInstanceInfo;
instance : PLuaInstanceInfo;
begin
result := nil;
instance:=nil;
try
if not lua_isuserdata(l, idx) then Exit;
obj_user:= lua_touserdata(L, idx);
if obj_user <> nil then
instance := obj_user^;
finally
if PopValue then
lua_pop(l, 1);
if assigned(instance) and assigned(instance^.obj) then
result := instance^.obj;
end;
end;
function plua_GlobalObjectGet(l: PLua_State; const varName: string): TObject;
var StartTop:Integer;
begin
Result:=nil;
StartTop:=lua_gettop(l);
try
lua_pushstring(L, PChar(varName));
lua_rawget(L, LUA_GLOBALSINDEX);
if lua_isuserdata(L, -1) then
begin
Result:=plua_getObject(l, -1, False);
end;
finally
lua_pop(L, 1);
plua_CheckStackBalance(l, StartTop);
end;
end;
function plua_getObjectTable(l: PLua_State; idx: Integer; PopValue: boolean
): TObjArray;
var
obj_user:PPLuaInstanceInfo;
instance : PLuaInstanceInfo;
C:Integer;
begin
SetLength(Result, 20);
C:=0;
//table traversal
//http://www.lua.org/manual/5.0/manual.html#3.5
// table is in the stack at index idx
lua_pushnil(L); // first key
while (lua_next(L, idx) <> 0) do
begin
// key is at index -2 and value at index -1
obj_user:= lua_touserdata(L, -1);
if obj_user <> nil then
begin