-
Notifications
You must be signed in to change notification settings - Fork 5
/
LuaWrapper.pas
1385 lines (1186 loc) · 36.3 KB
/
LuaWrapper.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 LuaWrapper;
interface
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$TYPEDADDRESS ON}
{$ENDIF}
{$I pLua.inc}
{$DEFINE TLuaAsComponent}
{$DEFINE TLuaHandlersAsIsObjectType}
uses
Classes, SysUtils,
lua,
pLua,
pLuaObject, pLuaRecord;
type
TLua = class;
TLuaOnException = procedure( Title: ansistring; Line: Integer; Msg: ansistring;
var handled : Boolean) {$IFDEF TLuaHandlersAsIsObjectType}of object{$ENDIF};
TLuaOnLoadLibs = procedure( LuaWrapper : TLua ) {$IFDEF TLuaHandlersAsIsObjectType}of object{$ENDIF};
{ TLUA }
TLUA=class{$IFDEF TLuaAsComponent}(TComponent){$ENDIF}
private
FOnException: TLuaOnException;
FOnLoadLibs: TLuaOnLoadLibs;
FUseDebug: Boolean;
FUserObj: TObject;
L : Plua_State;
FScript,
FLibFile,
FLibName: AnsiString;
FErrHandlerFunc: AnsiString;
FMethods : TStringList;
FErrHandler: Integer;
//Lua internal objects
FLuaObjects : TList;
FLuaClasses : TLuaClassList;
FLuaRecords : TLuaRecordList;
FintLuaRecords : TList;
FLuaDelegates : TList;
FClassTypesList : TLuaClassTypesList;
FRecordTypesList : TLuaRecordTypesList;
FLuaSelf : PLuaInstanceInfo;
procedure ClearObjects(LeakWarnings: boolean);
procedure ClearRecords;
function ExceptionBackTrace: string;
function GetLuaCPath: AnsiString;
function GetLuaPath: AnsiString;
function GetValue(valName : AnsiString): Variant;
procedure LoadScriptStr(const Script: string);
procedure PushErrorHandler;
procedure SetLibName(const Value: AnsiString);
procedure SetLuaCPath(const AValue: AnsiString);
procedure SetLuaPath(const AValue: AnsiString);
procedure OpenLibs;
procedure SetOnException(const AValue: TLuaOnException);
procedure SetOnLoadLibs(const AValue: TLuaOnLoadLibs);
procedure SetUseDebug(const AValue: Boolean);
procedure ErrorTest(errCode : Integer);
procedure HandleException(E : Exception);
procedure SetUserObj(AValue: TObject);
procedure SetValue(valName : AnsiString; const AValue: Variant);
procedure ExecuteScript(NArgs, NResults:integer);
public
constructor Create{$IFDEF TLuaAsComponent}(anOwner : TComponent); override;{$ENDIF}
{$IFDEF TLuaAsComponent}constructor Create;{$ENDIF}
destructor Destroy; override;
procedure Close;
procedure Open;
function Owns(Obj:TObject):boolean;
//mark given object as being ready for garbage collection
function ObjMarkFree(Obj:TObject):boolean;overload;
procedure ObjMarkFree(const Obj:TObjArray);overload;
//test internal state (global variable, etc)
procedure CheckIntegrity;
procedure GarbageCollect;
procedure LoadScript(const Script : AnsiString);
procedure LoadFile(const FileName:AnsiString);
//Loads function and saves it in lua state under given name.
//It's purpose is to run it multiple times without reloading.
procedure LoadFunctionFromFile(const FileName:string; const FunctionSaveAs:string);
procedure LoadFunctionFromScript(const Script:string; const FunctionSaveAs:string);
//Loads all functions with names FuncNames and bodies from FuncDumps
procedure LoadFunctionFromStrings(FuncNames:TStrings; FuncDumps:TStrings);
procedure Execute;
function ExecuteAsFunctionObj(const FunctionName:string):TObject;
function ExecuteAsFunctionObjList(const FunctionName:string):TObjArray;
procedure ExecuteAsFunctionStrList(const Script: string; ResultTable: TStrings; KeyTable:TStrings = nil);
procedure ExecuteAsFunction(const Script: string; const args:array of Variant; Results : PVariantArray = nil;
VariantHandler:TLuaVariantHandler = nil; CdataHandler:TLuaCdataHandler = nil);
procedure ExecuteCmd(Script:AnsiString);
procedure ExecuteAsRepl(const Script:String; out ReplResult:string);
procedure ExecuteFile(FileName : AnsiString);
//simple registering of C-function. No proper support for exception handling!!!
procedure RegisterLuaMethod(const aMethodName: AnsiString; Func: lua_CFunction);
//registering of pascal-function. Proper support for exception handling!!!
procedure RegisterLuaMethod(const aMethodName: AnsiString; Func: TLuaProc);
procedure RegisterLuaMethod(const aPackage, aMethodName: AnsiString; Func: TLuaProc);
procedure RegisterLuaTable(PropName: AnsiString; reader: lua_CFunction; writer : lua_CFunction = nil);
function FunctionExists(const aMethodName:AnsiString; TableIdx:Integer = LUA_GLOBALSINDEX) : Boolean;
function FunctionExists(const Package, aMethodName: AnsiString): Boolean;
function CallFunction( FunctionName :AnsiString;
const Args: array of Variant; //necessary to be able to call using [...] (array of const)
Results : PVariantArray = nil;
VariantHandler:TLuaVariantHandler = nil;
CdataHandler:TLuaCdataHandler = nil):Integer;overload;
function TableExists(const TableName:string):boolean;
function TableFunctionExists(TableName, FunctionName : AnsiString; out tblidx : Integer) : Boolean; overload;
function TableFunctionExists(TableName, FunctionName : AnsiString) : Boolean; overload;
function CallTableFunction( TableName, FunctionName :AnsiString;
const Args: array of Variant;
Results : PVariantArray = nil):Integer;
procedure ObjArraySet(const varName:String; const A:TObjArray; C: TLuaClassId; FreeGC:boolean = False; KeepRef:boolean = True);
procedure ObjSet(const varName:String; const O:TObject; C: TLuaClassId; FreeGC:boolean = False; KeepRef:boolean = True);
procedure ObjSetEmpty(const varName:String);
function ObjGet(const varName:string):TObject;
procedure GlobalVarClear(const varName:string);
procedure GlobalObjectNames(List: TStrings; LuaTypes: TLuaObjectTypes);
property ErrHandlerFunc : AnsiString read FErrHandlerFunc write FErrHandlerFunc;
property ScriptText: AnsiString read FScript write FScript;
property ScriptFile: AnsiString read FLibFile write FLibFile;
property LibName : AnsiString read FLibName write SetLibName;
property LuaState : Plua_State read L;
property LuaPath : AnsiString read GetLuaPath write SetLuaPath;
property LuaCPath : AnsiString read GetLuaCPath write SetLuaCPath;
property UseDebug : Boolean read FUseDebug write SetUseDebug;
property Value[valName : AnsiString] : Variant read GetValue write SetValue; default;
property OnException : TLuaOnException read FOnException write SetOnException;
property OnLoadLibs : TLuaOnLoadLibs read FOnLoadLibs write SetOnLoadLibs;
// singleton user-defined object. Freed on assign/destroy
property UserObj : TObject read FUserObj write SetUserObj;
end;
TLuaInternalState = class(TLua)
//class to be used by Lua handlers
public
property LuaObjects : TList read FLuaObjects;
property LuaClasses : TLuaClassList read FLuaClasses;
property intLuaRecords : TList read FintLuaRecords;
property LuaDelegates : TList read FLuaDelegates;
property LuaRecords : TLuaRecordList read FLuaRecords;
property ClassTypesList : TLuaClassTypesList read FClassTypesList;
property RecordTypesList : TLuaRecordTypesList read FRecordTypesList;
end;
{ TLUAThread }
TLUAThread=class
private
FMaster : TLUA;
FMethodName: AnsiString;
FTableName: AnsiString;
L : PLua_State;
FThreadName : AnsiString;
function GetIsValid: Boolean;
public
constructor Create(LUAInstance: TLUA; ThreadName : AnsiString);
destructor Destroy; override;
function Start(TableName : AnsiString; AMethodName : AnsiString; const ArgNames: array of AnsiString; var ErrorString : AnsiString) : Boolean;
function Resume(EllapsedTime : lua_Number; Args : array of Variant; var ErrorString : AnsiString) : Boolean;
property LuaState : Plua_State read L;
published
property IsValid : Boolean read GetIsValid;
property ThreadName : AnsiString read FThreadName;
property MethodName : AnsiString read FMethodName;
property TableName : AnsiString read FTableName;
end;
{ TLUAThreadList }
TLUAThreadList=class
private
FThreads : TList;
FLUAInstance : TLUA;
function GetCount: Integer;
function GetThread(index: integer): TLUAThread;
public
constructor Create(LUAInstance: TLUA);
destructor Destroy; override;
procedure Process(EllapsedTime : lua_Number; Args : array of Variant; var ErrorString : AnsiString);
function SpinUp(TableName, AMethodName, ThreadName : AnsiString; var ErrorString : AnsiString) : Boolean;
function IndexOf(ThreadName : AnsiString): Integer;
procedure Release(ThreadIndex : Integer);
property Thread[index:integer]: TLUAThread read GetThread;
published
property Count : Integer read GetCount;
end;
//To be used in Lua handlers
//Use carefully, it is global for Lua instance!!!
function LuaSelf(L : PLua_State):TLuaInternalState;
procedure LuaObjects_Free(S:TLuaInternalState; instance:PLuaInstanceInfo);
procedure LuaObjects_Add(S:TLuaInternalState; instance:PLuaInstanceInfo);
procedure LuaRecs_Free(S:TLuaInternalState; instance:PLuaRecordInstanceInfo);
implementation
uses
//Classes,
Variants;
const
Lua_Self = '__LuaWrapperSelf';
constructor TLUA.Create{$IFDEF TLuaAsComponent}(anOwner: TComponent){$ENDIF};
begin
{$IFDEF TLuaAsComponent}inherited;{$ENDIF}
FUseDebug := false;
FMethods := TStringList.Create;
FUserObj := nil;
FLuaObjects := TList.Create;
FLuaClasses := TLuaClassList.Create;
FintLuaRecords := TList.Create;
FLuaDelegates := TList.Create;
FLuaRecords := TLuaRecordList.Create;
FClassTypesList := TLuaClassTypesList.Create;
FRecordTypesList := TLuaRecordTypesList.Create;
FLibName:='main';
Open;
end;
{$IFDEF TLuaAsComponent}
constructor TLUA.Create;
begin
Create(nil);
end;
{$ENDIF}
procedure TLUA.ClearObjects(LeakWarnings:boolean);
// Frees/unregistered manually-tracked objects
var
i : Integer;
nfo : PLuaInstanceInfo;
begin
if FLuaObjects.Count > 0 then
Log('Warning!!! %d objects left unfreed.', [FLuaObjects.Count]);
i := FLuaObjects.Count-1;
while i > -1 do
begin
nfo := PLuaInstanceInfo(FLuaObjects[i]);
if LeakWarnings then
begin
//we cannot trust nfo^.obj is still valid here, so do not try to read ClassName via nfo^.obj.
//use only debug info when accesible.
if nfo^.LuaRef <> LUA_NOREF then
LogDebug('Lua object $%P (%s) has lua ref (%d) unfreed.',
[ Pointer(nfo^.obj), {$IFDEF DEBUG}nfo^.ClassName{$ELSE}'unknown'{$ENDIF}, nfo^.LuaRef ]);
LogDebug('Lua object $%P (%s) memory leak. Freeing...', [ Pointer(nfo^.obj), {$IFDEF DEBUG}nfo^.ClassName{$ELSE}'unknown'{$ENDIF} ]);
end;
try
LuaObjects_Free( TLuaInternalState(Self), nfo );
except
end;
dec(i);
end;
end;
procedure TLUA.ClearRecords;
var
i : Integer;
nfo : PLuaRecordInstanceInfo;
begin
i := FintLuaRecords.Count-1;
while i > -1 do
begin
nfo := PLuaRecordInstanceInfo(FintLuaRecords[i]);
if nfo^.l = l then
FintLuaRecords.Remove(nfo);
dec(i);
end;
end;
destructor TLUA.Destroy;
var instance:PLuaInstanceInfo;
rec_instance:PLuaRecordInstanceInfo;
begin
Close;
FreeAndNil(FUserObj);
FMethods.Free;
FreeAndNil(FLuaObjects);
FreeAndNil(FLuaClasses);
FreeAndNil(FintLuaRecords);
FreeAndNil(FLuaDelegates);
FreeAndNil(FLuaRecords);
FreeAndNil(FClassTypesList);
FreeAndNil(FRecordTypesList);
inherited;
end;
procedure TLUA.ExecuteScript(NArgs, NResults: integer);
var errCode:Integer;
msg:string;
begin
if L = nil then
Open;
try
if FErrHandler = -1 then
raise Exception.Create('No error handler installed');
if (lua_gettop(l) <= 0) or
(lua_type(L, lua_gettop(l) - Nargs) <> LUA_TFUNCTION) then
raise Exception.Create('No script is loaded at stack');
//ErrorTest(lua_pcall(L, 0, NResults, 0));
errCode:=lua_pcall(L, NArgs, NResults, FErrHandler);
if errCode <> 0 then
begin
msg := plua_tostring(l, -1);
HandleException(LuaException.Create(msg));
end;
finally
FErrHandler:=-1; //Make sure error handler is not re-used.
end;
end;
procedure TLUA.Execute;
begin
ExecuteScript(0,0);
end;
function TLUA.ExecuteAsFunctionObj(const FunctionName:string): TObject;
var tix:Integer;
StartTop:integer;
begin
Result:=nil;
StartTop:=lua_gettop(l);
try
PushErrorHandler;
//load function with name FunctionName on stack
lua_getglobal(l, PChar(FunctionName));
ExecuteScript(0,LUA_MULTRET);
tix:=lua_gettop(l);
if tix > 0 then
begin
if lua_type(L,-1) = LUA_TUSERDATA then
Result:=plua_getObject(l, tix)
else
lua_pop(l, 1);
end;
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
function TLUA.ExecuteAsFunctionObjList(const FunctionName: string): TObjArray;
var tix:Integer;
StartTop:integer;
O:TObject;
begin
SetLength(Result,0);
StartTop:=lua_gettop(l);
try
PushErrorHandler;
//load function with name FunctionName on stack
lua_getglobal(l, PChar(FunctionName));
ExecuteScript(0,LUA_MULTRET);
tix:=lua_gettop(l);
if tix > 0 then
begin
case lua_type(L,-1) of
LUA_TUSERDATA:
begin
O:=plua_getObject(l, tix);
SetLength(Result, 1);
Result[0]:=O;
end;
LUA_TTABLE:
begin
Result:=plua_getObjectTable(l, tix);
end;
else
lua_pop(l, 1);
end;
end;
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.LoadScriptStr(const Script:string);
//loads string on Lua stack
begin
//Can't use luaL_loadstring here, as Script can contain zeroes in bytecode strings
ErrorTest( luaL_loadbuffer(l, PChar(Script), Length(Script), 'dyn_str_script') );
end;
procedure TLUA.ExecuteAsFunctionStrList(const Script: string; ResultTable:TStrings; KeyTable:TStrings) ;
var StartTop:integer;
begin
ResultTable.Create;
StartTop:=lua_gettop(l);
try
PushErrorHandler;
LoadScriptStr(Script);
ExecuteScript(0,LUA_MULTRET);
plua_popstrings(l, ResultTable, KeyTable);
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.ExecuteAsFunction(const Script: string; const args: array of Variant; Results: PVariantArray;
VariantHandler:TLuaVariantHandler; CdataHandler:TLuaCdataHandler);
var StartTop, result_count, TopBeforeExecute:integer;
begin
StartTop:=lua_gettop(l);
try
PushErrorHandler;
TopBeforeExecute:=lua_gettop(l); //have to be called immediately before luaL_loadstring
LoadScriptStr(Script);
plua_pushvariants(l, args, False, VariantHandler);
ExecuteScript(Length(args), LUA_MULTRET);
if Results <> nil then
begin
result_count:=lua_gettop(l) - TopBeforeExecute;
Results^:=plua_popvariants(l, result_count, True, CdataHandler);
end;
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.ExecuteCmd(Script: AnsiString);
var StartTop:Integer;
begin
if L= nil then
Open;
StartTop:=lua_gettop(l);
try
PushErrorHandler;
ErrorTest(luaL_loadbuffer(L, PChar(Script), Length(Script), PChar(LibName)));
ExecuteScript(0,0);
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
function TLUA.ExceptionBackTrace:string;
var
FrameNumber,
FrameCount : longint;
Frames : PPointer;
begin
Result:='';
if RaiseList=nil then
exit;
Result:=BackTraceStrFunc(RaiseList^.Addr);
FrameCount:=RaiseList^.Framecount;
Frames:=RaiseList^.Frames;
for FrameNumber := 0 to FrameCount-1 do
Result:=Result + sLineBreak + BackTraceStrFunc(Frames[FrameNumber]);
end;
procedure TLUA.ExecuteAsRepl(const Script: String; out ReplResult: string);
var StartTop:Integer;
r:String;
ExceptThrown:boolean;
begin
ExceptThrown:=false;
ReplResult:='';
if L= nil then
Open;
StartTop:=lua_gettop(l);
try
try
PushErrorHandler;
ErrorTest(luaL_loadbuffer(L, PChar(Script), Length(Script), PChar(LibName)));
ExecuteScript(0,LUA_MULTRET); // LUA_MULTRET - нас интересуют _все_ результаты
except
on E:Exception do
begin
ReplResult:=E.Message + sLineBreak + ExceptionBackTrace;
ExceptThrown:=true;
end;
end;
//пока есть результаты - продолжаем выталкивать из стека
while lua_gettop(l) <> StartTop do
begin
if (not ExceptThrown) and (lua_type(L,-1) = LUA_TSTRING) then
begin
r := plua_tostring(l, -1);
ReplResult:=r + sLineBreak + ReplResult; //последний результат лежит на верху стека
end;
lua_pop(l, 1);
end;
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.ExecuteFile(FileName: AnsiString);
var
StartTop: Integer;
F:TFileStream;
S:string;
Size:int64;
begin
if L = nil then
Open;
StartTop:=lua_gettop(l);
try
PushErrorHandler;
{
// does not work with multiple processes/threads reading source file simultaneously...
ErrorTest(luaL_loadfile(L, PChar(FileName)));
}
F:=TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Size:=F.Size;
SetLength(S, Size);
F.ReadBuffer((@S[1])^, Size);
ErrorTest(luaL_loadbuffer(L, @S[1], Size, PChar(FileName)));
ExecuteScript(0,0);
finally
FreeAndNil(F);
end;
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.SetLuaPath(const AValue: AnsiString);
begin
lua_pushstring(L, 'package');
lua_gettable(L, LUA_GLOBALSINDEX);
lua_pushstring(L, 'path');
lua_pushstring(L, PChar(AValue));
lua_settable(L, -3);
end;
procedure TLUA.LoadFile(const FileName: AnsiString);
var StartTop:integer;
begin
if L = nil then
Open;
StartTop:=lua_gettop(l);
FLibFile := FileName;
FScript := '';
ErrorTest( luaL_loadfile(L, PChar(FileName)) );
plua_CheckStackBalance(l, StartTop+1);
end;
procedure TLUA.LoadFunctionFromFile(const FileName: string; const FunctionSaveAs:string);
var StartTop:integer;
begin
StartTop:=lua_gettop(l);
LoadFile(FileName);
lua_setglobal(L, PChar(FunctionSaveAs));
plua_CheckStackBalance(l, StartTop);
end;
procedure TLUA.LoadFunctionFromScript(const Script: string;
const FunctionSaveAs: string);
var StartTop:integer;
begin
StartTop:=lua_gettop(l);
LoadScript(Script);
lua_setglobal(L, PChar(FunctionSaveAs));
plua_CheckStackBalance(l, StartTop);
end;
procedure TLUA.LoadFunctionFromStrings(FuncNames: TStrings; FuncDumps: TStrings);
var i:Integer;
StartTop:integer;
begin
StartTop:=lua_gettop(l);
for i:=0 to FuncNames.Count-1 do
begin
LoadScriptStr(FuncDumps.Strings[i]);
lua_setglobal(L, PChar(FuncNames.Strings[i]));
end;
plua_CheckStackBalance(l, StartTop);
end;
procedure TLUA.LoadScript(const Script: AnsiString);
var StartTop:integer;
begin
if FScript <> Script then
Close;
if L = nil then
Open;
StartTop:=lua_gettop(l);
FScript := Trim(Script);
if FScript = '' then Exit;
FLibFile := '';
luaL_loadbuffer(L, PChar(Script), length(Script), PChar(LibName));
plua_CheckStackBalance(l, StartTop + 1);
end;
function TLUA.FunctionExists(const Package, aMethodName: AnsiString): Boolean;
var TopToBe, TableIdx:Integer;
begin
Result := False;
TopToBe:=lua_gettop(l);
try
lua_pushstring(L, PChar(Package));
lua_gettable(L, LUA_GLOBALSINDEX);
if lua_isnil(L, -1) then Exit;
TableIdx:=lua_gettop(l);
Result:=FunctionExists(aMethodName, TableIdx);
finally
plua_EnsureStackBalance(l, TopToBe);
end;
end;
function TLUA.FunctionExists(const aMethodName: AnsiString; TableIdx:Integer = LUA_GLOBALSINDEX): Boolean;
begin
lua_pushstring(L, PChar(aMethodName));
lua_rawget(L, TableIdx);
result := (not lua_isnil(L, -1)) and lua_isfunction(L, -1);
lua_pop(L, 1);
end;
procedure TLUA.RegisterLuaMethod(const aMethodName: AnsiString; Func: lua_CFunction);
begin
if L = nil then
Open;
lua_register(L, PChar(aMethodName), Func);
if FMethods.IndexOf(aMethodName) = -1 then
FMethods.AddObject(aMethodName, TObject(@Func))
else
FMethods.Objects[FMethods.IndexOf(aMethodName)] := TObject(@Func);
end;
procedure TLUA.RegisterLuaMethod(const aMethodName: AnsiString; Func: TLuaProc);
begin
if L = nil then
Open;
plua_RegisterMethod(l, aMethodName, Func);
end;
procedure TLUA.RegisterLuaMethod(const aPackage, aMethodName: AnsiString; Func: TLuaProc);
begin
if L = nil then
Open;
plua_RegisterMethod(l, aPackage, aMethodName, Func);
end;
procedure TLUA.RegisterLuaTable(PropName: AnsiString; reader: lua_CFunction;
writer: lua_CFunction);
begin
plua_RegisterLuaTable(l, PropName, reader, writer);
end;
procedure TLUA.SetLibName(const Value: AnsiString);
begin
FLibName := Value;
end;
procedure TLUA.SetLuaCPath(const AValue: AnsiString);
begin
lua_pushstring(L, 'package');
lua_gettable(L, LUA_GLOBALSINDEX);
lua_pushstring(L, 'cpath');
lua_pushstring(L, PChar(AValue));
lua_settable(L, -3);
end;
function TLUA.GetLuaPath: AnsiString;
begin
lua_pushstring(L, 'package');
lua_gettable(L, LUA_GLOBALSINDEX);
lua_pushstring(L, 'path');
lua_rawget(L, -2);
result := AnsiString(lua_tostring(L, -1));
end;
function TLUA.GetValue(valName : AnsiString): Variant;
var StartTop:Integer;
begin
StartTop:=lua_gettop(l);
result := NULL;
lua_pushstring(l, PChar(valName));
lua_rawget(l, LUA_GLOBALSINDEX);
try
result := plua_tovariant(l, -1);
finally
lua_pop(l, 1);
end;
plua_CheckStackBalance(l, StartTop);
end;
function TLUA.GetLuaCPath: AnsiString;
begin
lua_pushstring(L, 'package');
lua_gettable(L, LUA_GLOBALSINDEX);
lua_pushstring(L, 'cpath');
lua_rawget(L, -2);
result := AnsiString(lua_tostring(L, -1));
end;
function TLUA.CallFunction(FunctionName: AnsiString;
const Args: array of Variant; Results: PVariantArray = nil;
VariantHandler:TLuaVariantHandler = nil; CdataHandler:TLuaCdataHandler = nil): Integer;
var Package, FName:string;
TopToBe:Integer;
TableIdx:Integer;
begin
result := -1;
TopToBe:=lua_gettop(l);
try
try
//get a stack trace in case of error
PushErrorHandler;
//function name is complex - then first push its table on stack
plua_FuncNameParse(FunctionName, Package, FName);
if Package = '' then
begin
if FunctionExists(FunctionName) then
result := plua_callfunction(L, FunctionName, Args, Results, LUA_GLOBALSINDEX, FErrHandler, nil, VariantHandler, CdataHandler );
end
else
begin
if FunctionExists(Package, FName) then
begin
lua_pushstring(L, PChar(Package));
lua_gettable(L, LUA_GLOBALSINDEX);
TableIdx:=lua_gettop(l);
result := plua_callfunction(L, FName, Args, Results, TableIdx, FErrHandler, nil, VariantHandler, CdataHandler);
end;
end;
except
on E:Exception do
HandleException(E);
end;
finally
//error handler should be cleared here as well
plua_EnsureStackBalance(l, TopToBe);
end;
end;
function TLUA.TableExists(const TableName:string): boolean;
begin
Result:=pLua_TableExists(l, TableName);
end;
procedure TLUA.Close;
begin
FErrHandler:=-1;
if L <> nil then
begin
lua_close(L);
L := nil;
ClearObjects(True);
ClearRecords;
if FLuaSelf <> nil then
begin
plua_instance_free(nil, FLuaSelf);
end;
end;
FLibFile:='';
FScript:='';
end;
procedure TLUA.PushErrorHandler;
var Package, FName : string;
std_handler : boolean;
begin
std_handler := true;
if FErrHandlerFunc <> '' then
begin
plua_FuncNameParse(FErrHandlerFunc, Package, FName);
std_handler :=not ( (Package <> '') and (FName <> '') and FunctionExists(Package, FName) );
end;
if std_handler then
begin
// standard Lua stack tracer by default
Package := 'debug';
FName := 'traceback';
end;
//push error handler on stack to be able to reference it everywhere
// http://tinylittlelife.org/?p=254
lua_getglobal(L, PChar(Package));
//-1 is the top of the stack
lua_getfield(L, -1, PChar(FName));
//traceback is on top, remove package name from 2nd spot
lua_remove(L, -2);
FErrHandler:=lua_gettop(L);
end;
procedure TLUA.Open;
begin
if L <> nil then
Close;
L := lua_open;
OpenLibs;
//Register self in Lua VM to be able call from Lua code/native handlers
FLuaSelf:=plua_pushexisting_special(l, Self, nil, False);
lua_setglobal( L, PChar(Lua_Self) );
end;
function LuaSelf(L: PLua_State): TLuaInternalState;
{$OBJECTCHECKS OFF} // Harmless while no additional fields/virtual functions vs. TLua class added
var StartTop:Integer;
p:TObject;
begin
StartTop:=lua_gettop(l);
p:=plua_GlobalObjectGet(l, Lua_Self);
//global VM object MUST BE registered, otherwise something really wrong.
if p = nil then
plua_RaiseException(l, StartTop, 'Global Lua VM Self pointer is not registered');
if p.ClassType <> TLUA then
plua_RaiseException(l, StartTop, 'Global Lua VM Self must be of type %s, but has type %s', [TLUA.ClassName, p.ClassName]);
plua_CheckStackBalance(l, StartTop);
Result:=TLuaInternalState(p);
end;
procedure LuaObjects_Add(S:TLuaInternalState; instance:PLuaInstanceInfo);
begin
S.LuaObjects.Add( instance );
{$IFDEF DEBUG_LUA}
DumpStackTrace;
{$ENDIF}
end;
procedure LuaRecs_Free(S: TLuaInternalState; instance: PLuaRecordInstanceInfo);
var RecInfo:PLuaRecordInfo;
begin
if instance^.OwnsInstance then
begin
RecInfo:=S.LuaRecords.RecInfoById[ instance^.RecordId ];
RecInfo^.Release(instance^.RecordPointer, nil);
end;
Freemem(instance);
end;
procedure LuaObjects_Free(S:TLuaInternalState; instance:PLuaInstanceInfo);
var i:integer;
C:PLuaClassInfo;
begin
i:=S.LuaObjects.IndexOf(instance);
if i <> -1 then
begin
if instance^.OwnsObject then
begin
C:= S.LuaClasses.ClassInfoById[ instance^.ClassId ];
if assigned(C^.Release) then
C^.Release(instance^.obj, nil)
else
instance^.obj.Free;
end;
if Instance^.Delegate <> nil then
Instance^.Delegate.Free;
Dispose(instance);
S.LuaObjects.Delete(i);
end;
end;
function TLUA.Owns(Obj: TObject): boolean;
var info:PLuaInstanceInfo;
begin
Result:=False;
info:=plua_GetObjectInfo(l, Obj);
if info = nil then Exit;
Result:=info^.OwnsObject;
end;
function TLUA.ObjMarkFree(Obj: TObject):boolean;
begin
Result:=False;
if l <> nil then
Result:=plua_ObjectMarkFree(l, Obj);
end;
procedure TLUA.ObjMarkFree(const Obj: TObjArray);
var n:integer;
begin
if l <> nil then
for n:=0 to High(Obj) do
plua_ObjectMarkFree(l, Obj[n]);
end;
procedure TLUA.CheckIntegrity;
begin
//Lua Self has its own checks
LuaSelf(l);
end;
procedure TLUA.GarbageCollect;
begin
if l <> nil then
lua_gc(l, LUA_GCCOLLECT, 0);
end;
procedure TLUA.OpenLibs;
var
I : Integer;
begin
luaL_openlibs(L);
if UseDebug then
luaopen_debug(L);
lua_settop(L, 0);
for I := 0 to FMethods.Count -1 do
RegisterLUAMethod(FMethods[I], lua_CFunction(Pointer(FMethods.Objects[I])));
FRecordTypesList.RegisterTo(L);
FClassTypesList.RegisterTo(L);
if assigned(FOnLoadLibs) then
FOnLoadLibs(self);
end;
procedure TLUA.SetOnException(const AValue: TLuaOnException);
begin
if FOnException=AValue then exit;
FOnException:=AValue;
end;