Массивы FastScript поддерживает все типы массивов: статические (одномерные, многомерные), динамические, вариантные. Вот пример скрипта, использующего три массива целых чисел, объявленных разным способом:
Code
var
ar1: array[0..2] of Integer;
ar2: array of Integer;
ar3: Variant;
SetLength(ar2, 3);
ar3 := VarArrayCreate([0, 2], varInteger);
ar1[0] := 1;
ar2[0] := 1;
ar3[0] := 1;
Доступные классы
Из модуля Classes:
TObject
constructor TObject.Create
procedure TObject.Free
TPersistent
procedure TPersistent.Assign(Source: TPersistent)
TList
function TList.Add(Item: TObject): Integer
procedure TList.Clear
procedure TList.Delete(Index: Integer)
function TList.IndexOf(Item: TObject): Integer
procedure TList.Insert(Index: Integer; Item: TObject)
function TList.Remove(Item: TObject): Integer
property TList.Count
property TList.Items
TStrings
function TStrings.Add(const S: string): Integer
function TStrings.AddObject(const S: string; AObject: TObject): Integer
procedure TStrings.Clear
procedure TStrings.Delete(Index: Integer)
function TStrings.IndexOf(const S: string): Integer
function TStrings.IndexOfName(const Name: string): Integer
function TStrings.IndexOfObject(AObject: TObject): Integer
procedure TStrings.Insert(Index: Integer; const S: string)
procedure TStrings.InsertObject(Index: Integer; const S: string; AObject: TObject)
procedure TStrings.LoadFromFile(const FileName: string)
procedure TStrings.LoadFromStream(Stream: TStream)
procedure TStrings.SaveToFile(const FileName: string)
procedure TStrings.SaveToStream(Stream: TStream)
property TStrings.CommaText
property TStrings.Count
property TStrings.Names
property TStrings.Objects
property TStrings.Values
property TStrings.Strings
property TStrings.Text
TStringList
function TStringList.Find(s: String; var Index: Integer): Boolean
procedure TStringList.Sort
property TStringList.Duplicates
property TStringList.Sorted
TStream
function TStream.Read(Buffer: string; Count: Longint): Longint
function TStream.Write(Buffer: string; Count: Longint): Longint
function TStream.Seek(Offset: Longint; Origin: Word): Longint
function TStream.CopyFrom(Source: TStream; Count: Longint): Longint
property TStream.Position
property TStream.Size
TFileStream
constructor TFileStream.Create(Filename: String; Mode: Word)
TMemoryStream
procedure TMemoryStream.Clear
procedure TMemoryStream.LoadFromStream(Stream: TStream)
procedure TMemoryStream.LoadFromFile(Filename: String)
procedure TMemoryStream.SaveToStream(Stream: TStream)
procedure TMemoryStream.SaveToFile(Filename: String)
TComponent
constructor TComponent.Create(AOwner: TComponent)
property TComponent.Owner
TfsXMLItem
constructor TfsXMLItem.Create
procedure TfsXMLItem.AddItem(Item: TfsXMLItem)
procedure TfsXMLItem.Clear
procedure TfsXMLItem.InsertItem(Index: Integer; Item: TfsXMLItem)
function TfsXMLItem.Add: TfsXMLItem
function TfsXMLItem.Find(const Name: String): Integer
function TfsXMLItem.FindItem(const Name: String): TfsXMLItem
function TfsXMLItem.Prop(const Name: String): String
function TfsXMLItem.Root: TfsXMLItem
property TfsXMLItem.Data
property TfsXMLItem.Count
property TfsXMLItem.Items
property TfsXMLItem.Name
property TfsXMLItem.Parent
property TfsXMLItem.Text
TfsXMLDocument
constructor TfsXMLDocument.Create
procedure TfsXMLDocument.SaveToStream(Stream: TStream)
procedure TfsXMLDocument.LoadFromStream(Stream: TStream)
procedure TfsXMLDocument.SaveToFile(const FileName: String)
procedure TfsXMLDocument.LoadFromFile(const FileName: String)
property TfsXMLDocument.Root
const fmCreate
const fmOpenRead
const fmOpenWrite
const fmOpenReadWrite
const fmShareExclusive
const fmShareDenyWrite
const fmShareDenyNone
const soFromBeginning
const soFromCurrent
const soFromEnd
type TDuplicates
Из модуля Graphics:
TFont
TPen
TBrush
TCanvas
procedure TCanvas.Draw(X, Y: Integer; Graphic: TGraphic)
procedure TCanvas.Ellipse(X1, Y1, X2, Y2: Integer)
procedure TCanvas.LineTo(X, Y: Integer)
procedure TCanvas.MoveTo(X, Y: Integer)
procedure TCanvas.Rectangle(X1, Y1, X2, Y2: Integer)
procedure TCanvas.RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer)
procedure TCanvas.StretchDraw(X1, Y1, X2, Y2: Integer; Graphic: TGraphic)
function TCanvas.TextHeight(const Text: string): Integer
procedure TCanvas.TextOut(X, Y: Integer; const Text: string)
function TCanvas.TextWidth(const Text: string): Integer
property TCanvas.Pixels
TGraphic
procedure TGraphic.LoadFromFile(const Filename: string)
procedure TGraphic.SaveToFile(const Filename: string)
property TGraphic.Height
property TGraphic.Width
TMetafile
TMetafileCanvas
TBitmap
property TBitmap.Canvas
type TFontStyles
type TFontPitch
type TPenStyle
type TPenMode
type TBrushStyle
Из модулей StdCtrls и Forms:
TControl
property TControl.Parent
procedure TControl.Hide
procedure TControl.Show
procedure TControl.SetBounds(ALeft, ATop, AWidth, AHeight: Integer)
event TControl.OnCanResize
event TControl.OnClick
event TControl.OnDblClick
event TControl.OnMouseDown
event TControl.OnMouseMove
event TControl.OnMouseUp
event TControl.OnResize
TWinControl
procedure TWinControl.SetFocus
event TWinControl.OnEnter
event TWinControl.OnExit
event TWinControl.OnKeyDown
event TWinControl.OnKeyPress
event TWinControl.OnKeyUp
TCustomControl
TGraphicControl
TGroupBox
TLabel
TEdit
TMemo
TCustomComboBox
property TCustomComboBox.DroppedDown
property TCustomComboBox.ItemIndex
TComboBox
TButton
TCheckBox
TRadioButton
TCustomListBox
property TCustomListBox.ItemIndex
property TCustomListBox.SelCount
property TCustomListBox.Selected
TListBox
TControlScrollBar
TScrollingWinControl
TScrollBox
TCustomForm
procedure TCustomForm.Close
procedure TCustomForm.Hide
procedure TCustomForm.Show
function TCustomForm.ShowModal: Integer
event TCustomForm.OnActivate
event TCustomForm.OnClose
event TCustomForm.OnCloseQuery
event TCustomForm.OnCreate
event TCustomForm.OnDestroy
event TCustomForm.OnDeactivate
event TCustomForm.OnHide
event TCustomForm.OnPaint
event TCustomForm.OnShow
property TCustomForm.ModalResult
TForm
type TModalResult
type TCursor
type TShiftState
type TAlignment
type TAlign
type TMouseButton
type TAnchors
type TBevelCut
type TTextLayout
type TEditCharCase
type TScrollStyle
type TComboBoxStyle
type TCheckBoxState
type TListBoxStyle
type TFormBorderStyle
type TWindowState
type TFormStyle
type TBorderIcons
type TPosition
type TCloseAction
Из модуля ExtCtrls:
TShape
TPaintBox
event TPaintBox.OnPaint
TImage
TBevel
TTimer
event TTimer.OnTimer
TPanel
TSplitter
TBitBtn
TSpeedButton
TCheckListBox
property TCheckListBox.Checked
TTabControl
TTabSheet
TPageControl
procedure TPageControl.SelectNextPage(GoForward: Boolean)
property TPageControl.PageCount
property TPageControl.Pages
TStatusPanel
TStatusPanels
function TStatusPanels.Add: TStatusPanel
property TStatusPanels.Items
TStatusBar
TTreeNode
procedure TTreeNode.Delete
function TTreeNode.EditText: Boolean
property TTreeNode.Count
property TTreeNode.Data
property TTreeNode.ImageIndex
property TTreeNode.SelectedIndex
property TTreeNode.StateIndex
property TTreeNode.Text
TTreeNodes
function TTreeNodes.Add(Node: TTreeNode; const S: string): TTreeNode
function TTreeNodes.AddChild(Node: TTreeNode; const S: string): TTreeNode
procedure TTreeNodes.BeginUpdate
procedure TTreeNodes.Clear
procedure TTreeNodes.Delete(Node: TTreeNode)
procedure TTreeNodes.EndUpdate
property TTreeNodes.Count
property TTreeNodes.Item
TTreeView
procedure TTreeView.FullCollapse
procedure TTreeView.FullExpand
property TTreeView.Selected
property TTreeView.TopItem
TTrackBar
TProgressBar
TListColumn
TListColumns
function TListColumns.Add: TListColumn
property TListColumns.Items
TListItem
procedure TListItem.Delete
function TListItem.EditCaption: Boolean
property TListItem.Caption
property TListItem.Checked
property TListItem.Data
property TListItem.ImageIndex
property TListItem.Selected
property TListItem.StateIndex
property TListItem.SubItems
TListItems
function TListItems.Add: TListItem
procedure TListItems.BeginUpdate
procedure TListItems.Clear
procedure TListItems.Delete(Index: Integer)
procedure TListItems.EndUpdate
property TListItems.Count
property TListItems.Item
TIconOptions
TListView
TToolButton
TToolBar
TMonthCalColors
TDateTimePicker
TMonthCalendar
type TShapeType
type TBevelStyle
type TBevelShape
type TResizeStyle
type TButtonLayout
type TButtonState
type TButtonStyle
type TBitBtnKind
type TNumGlyphs
type TTabPosition
type TTabStyle
type TStatusPanelStyle
type TStatusPanelBevel
type TSortType
type TTrackBarOrientation
type TTickMark
type TTickStyle
type TProgressBarOrientation
type TIconArrangement
type TListArrangement
type TViewStyle
type TToolButtonStyle
type TDateTimeKind
type TDTDateMode
type TDTDateFormat
type TDTCalAlignment
type TCalDayOfWeek
Из модуля Dialogs:
TCommonDialog
function TCommonDialog.Execute: Boolean
TOpenDialog
TSaveDialog
TColorDialog
TFontDialog
TPrintDialog
TPrinterSetupDialog
type TOpenOptions
type TFileEditStyle
type TColorDialogOptions
type TFontDialogOptions
type TFontDialogDevice
type TPrintRange
type TPrintDialogOptions
Вы имеете доступ ко всем published свойствам этих классов + доступ к некоторым public свойствам и методам.
Перечень добавляемых ПХ в движек FastScript:
Code
function HStr(Hex:String):String
procedure SendToClient
procedure SendToServer
procedure SendToClientEx(CharName:string)
procedure SendToServerEx(CharName:string)
procedure NoCloseFrameAfterDisconnect
procedure CloseFrameAfterDisconnect
procedure NoCloseClientAfterServerDisconnect
procedure CloseClientAfterServerDisconnect
procedure NoCloseServerAfterClientDisconnect
procedure CloseServerAfterClientDisconnect
procedure Disconnect
function ConnectNameByID(id:integer):string
function ConnectIDByName(name:string):integer
procedure SetName(Name:string)
procedure Delay(msec: Cardinal)
procedure ShowForm
procedure HideForm
procedure WriteS(v:string)
procedure WriteC(v:byte; ind:integer=0)
procedure WriteD(v:integer; ind:integer=0)
procedure WriteH(v:word; ind:integer=0)
procedure WriteF(v:double; ind:integer=0)
function ReadS(var index:integer):string
function ReadC(var index:integer):byte
function ReadD(var index:integer):integer
function ReadH(var index:integer):word
function ReadF(var index:integer):double
procedure sendMSG(msg:String)
procedure CanUseAltTab(FormCaption: string)
function LoadLibrary(LibName:String):Integer
function FreeLibrary(LibHandle:Integer):Boolean
function StrToHex(str1:String):String
procedure CallPr(LibHandle:integer;FunctionName:String;Count:Integer;Params:array of variant)
function CallFnc(LibHandle:integer;FunctionName:String;Count:Integer;Params:array of variant):string
procedure TestFunc(LibHandle:integer;FunctionName:String;Count:Integer)
procedure TestFunc1(LibHandle:integer;FunctionName:String;Count1:variant)
function CallFunction(LibHandle:integer;FunctionName:String;Count:Integer;Params:array of variant):variant
function CallSF(ScriptName:String;FunctionName:String;Params:array of variant):variant
Имеющиеся в FastScript согласно официального мануала
Code
function IntToStr(i: Integer): String;
function FloatToStr(e: Extended): String;
function DateToStr(e: Extended): String;
function TimeToStr(e: Extended): String;
function DateTimeToStr(e: Extended): String;
function VarToStr(v: Variant): String;
function StrToInt(s: String): Integer;
function StrToFloat(s: String): Extended;
function StrToDate(s: String): Extended;
function StrToTime(s: String): Extended;
function StrToDateTime(s: String): Extended;
function Format(Fmt: String; Args: array): String;
function FormatFloat(Fmt: String; Value: Extended): String;
function FormatDateTime(Fmt: String; DateTime: TDateTime): String;
function FormatMaskText(EditMask: string; Value: string): string;
function EncodeDate(Year, Month, Day: Word): TDateTime;
procedure DecodeDate(Date: TDateTime; var Year, Month, Day: Word);
function EncodeTime(Hour, Min, Sec, MSec: Word): TDateTime;
procedure DecodeTime(Time: TDateTime; var Hour, Min, Sec, MSec: Word);
function Date: TDateTime;
function Time: TDateTime;
function Now: TDateTime;
function DayOfWeek(aDate: DateTime): Integer;
function IsLeapYear(Year: Word): Boolean;
function DaysInMonth(nYear, nMonth: Integer): Integer;
function Length(s: String): Integer;
function Copy(s: String; from, count: Integer): String;
function Pos(substr, s: String): Integer;
procedure Delete(var s: String; from, count: Integer);
procedure Insert(s: String; var s2: String; pos: Integer);
function Uppercase(s: String): String;
function Lowercase(s: String): String;
function Trim(s: String): String;
function NameCase(s: String): String;
function CompareText(s, s1: String): Integer;
function Chr(i: Integer): Char;
function Chr(i: Integer): Char;
function Ord(ch: Char): Integer;
procedure SetLength(var S: String; L: Integer);
function Round(e: Extended): Integer;
function Trunc(e: Extended): Integer;
function Int(e: Extended): Integer;
function Frac(X: Extended): Extended;
function Sqrt(e: Extended): Extended;
function Abs(e: Extended): Extended;
function Sin(e: Extended): Extended;
function Cos(e: Extended): Extended;
function ArcTan(X: Extended): Extended;
function Tan(X: Extended): Extended;
function Exp(X: Extended): Extended;
function Ln(X: Extended): Extended;
function Pi: Extended;
procedure Inc(var i: Integer; incr: Integer = 1);
procedure Dec(var i: Integer; decr: Integer = 1);
procedure RaiseException(Param: String);
procedure ShowMessage(Msg: Variant);
procedure Randomize;
function Random: Extended;
function ValidInt(cInt: String): Boolean;
function ValidFloat(cFlt: String): Boolean;
function ValidDate(cDate: String): Boolean;
function CreateOleObject(ClassName: String): Variant;
function VarArrayCreate(Bounds: Array; Typ: Integer): Variant;
Перечень переменных добавляемых ПХ:
Code
var buf: string;
var pck: string;
const FromServer: Boolean;
const FromClient: Boolean;
const ConnectID: Integer;
const ConnectName: string;
Доступные переменные:
pck (string) - текущий обрабатываемый пакет (без первых двух байт с размером)
FromClient (boolean) - пакет (pck) пришел от клиента (всёравно что not FromServer)
FromServer (boolean) - пакет (pck) пришел от сервера (всёравно что not FromClient)
buf (string) - буфер, используемый некоторыми функциями
ConnectName (string) - имя чара от или к которому идёт пакет (v. 3.1.3+)
ConnectID (integer) - номер соединения для которого выполняется скрипт
Доступные функции:
ShowForm и HideForm - для отображения/скрытия формы (UserForm), управлять которой можно из скрипта
Для рисования на ней контролов надо указывать UserForm в качестве родителя
SendToClient - отправляет клиенту содержимое переменной buf
SendToServer - отправляет серверу содержимое переменной buf
SendToClientEx(CharName: string) - отправляет клиенту с именем CharName содержимое переменной buf (v. 3.1.3+)
SendToServerEx(CharName: string) - отправляет серверу с именем CharName содержимое переменной buf (v. 3.1.3+)
(к пакету buf автоматически добавляются 2 байта длины)
CanUseAltTab(FormCaption: string) - Добавляет форму созданую в скрипте в список форм видимых по alt+tab. в качестве параметра - заголовок формы. (v. 3.5.1+)
NoCloseServerAfterClientDisconnect - запрещает закрытие соединения при дисконекте клиента (v. 3.5.1+)
NoCloseClientAfterServerDisconnect - запрещает закрытие соединения при дисконекте сервера (v. 3.5.1+)
CloseServerAfterClientDisconnect - разрешает закрытие соединения при дисконекте клиента (v. 3.5.1+)
CloseClientAfterServerDisconnect - разрешает закрытие соединения при дисконекте сервера (v. 3.5.1+)
(по умолчанию закрытия разрешены)
Disconnect - закрывает соединение (v. 3.5.1+)
ConnectNameByID(id:integer):string - возвращает имя соединения по его ID (v. 3.2.0+)
ConnectIDByName(name:string):integer - возвращает ID соединения по его имени (v. 3.2.0+)
SetName(Name:string) - устанавливает имя соединения (v. 3.2.0+)
ReadC(var index:integer):byte - читает из переменной pck байт
ReadH(var index:integer):word - читает из переменной pck число (2 байта) (v. 3.1.8+)
ReadD(var index:integer):integer - читает из переменной pck число (4 байта)
ReadF(var index:integer)ouble - читает из переменной pck число c плавающей запятой(8 байт) (v. 3.1.8+)
ReadS(var index:integer):string - читает из переменной pck строку (в пакете строка unicode нультерминированная, а результирующая строка обычная паскалевская)
Index - начальная позиция чтения, которая модифицируется функцией (сдвигается на число считанных байт)
HStr(h:string):string - преобразует строку в HEX-последовательность
К примеру, HStr('AA 00 BB 00 CC 00') вернёт цепочку байт #$AA#$00#$BB#$00#$CC#$00. Можно передавать строку как с пробелами, так и без них; регистр символов не имеет значения.
Code
WriteC(v:byte; ind:integer=0) - пишет в переменную buf один байт
WriteH(v:word; ind:integer=0) - пишет в переменную buf число (2 байта) (v. 3.1.8+)
WriteD(v:integer; ind:integer=0) - пишет в переменную buf число (4 байта)
WriteF(v:double; ind:integer=0) - пишет в переменную buf число c плавающей запятой(8 байт) (v. 3.1.8+)
WriteS(v:string) - пишет в переменную buf строку (автоматический перевод в unicode)
В первых четырёх процедурах присутствует необязательный параметр ind. Если параметр не указан, то переменная buf дополняется байтом/числом, иначе модифицируется часть буфера.
sendMSG(msg:String) - пишет msg в лог ПХ.
LoadLibrary(LibName:String):Integer - подгружает к программе библиотеку LibName и возвращает указатель на неё (v. 3.1.8+)
FreeLibrary(LibHandle:Integer):Boolean - выгружает из памяти программы библиотеку (v. 3.1.8+)
CallFnc(LibHandle:integer;FunctionName:String;Coun t:Integ er;Params:array of variant):String- вызывает функцию FunctionName из зарание подгруженной библиотеки с указателем LibHandle и параметрами перечисленными в Params (v. 3.5.1+)
CallPr(LibHandle:integer;FunctionName:String;Count :Integ er;Params:array of variant);- вызывает процедуру FunctionName из зарание подгруженной библиотеки с указателем LibHandle и параметрами перечисленными в Params (v. 3.5.1+)
CallSF(ScriptName:String;FunctionName:String;Param s:array of variant):variant - вызывет функцию FunctionName из скрипта ScriptName (v. 3.5.1+)
Пример:
buf=HStr('AA BB CC DD EE');
Если вызвать функцию WriteD(10,1), то получим buf=[0A 00 00 00 EE].
А если просто WriteD(10), то [AA BB CC DD EE 0A 00 00 00].
Например скрипт:
Code
begin
if FromClient and (ConnectName='SokolA')
and (pck=HStr('1b 04 00 00 00')) then begin
buf:=HStr('45 00 00 00 00 00 00 00 00 00');
SendToServerEx('SokolB');
pck:='';
end;
end.
При получении от клиента играющего за чара с ником SokolA пакета 1b 04 00 00 00 (социальное действие "Victory") непропустит этот пакет и отправит пакет 45 00 00 00 00 00 00 00 00 00 (команда сесть) от имени клиента играющего за чара с ником SokolB, тоесть играете вы в два окна, в одном SokolA, в другом SokolB, нажимаете в первом Victory, и SokolB садится.
Пример вызова функций из системных библиотек:
Code
var
lib,Lib1:Integer;
Res:variant;
ar:array of variant;
begin
lib := loadLibrary('User32.dll');
lib1 := loadLibrary('GDI32.dll');
Res := CallFunction(lib,'MessageBoxW',4,[nil,'Text1','text2',0]);
Res := CallFunction(lib,'GetDC',1,[0]);
CallFunction(lib1,'LineTo',3,[Res,100,100]);
CallFunction(lib,'ReleaseDC',2,[0,Res]);
FreeLibrary(lib);
FreeLibrary(lib1);
end.
Скрипты:
Процедура Init вызывается когда вы устанавливаете рядом со скриптом галочку. либо вызываете TestInit.
Процедура Free вызывается когда вы убираете рядом со скриптом галочку. либо вызываете TestFree.
Основное тело скрипта (между begin и end) вызывается каждый раз при получении пакета от сервера или клиента если скрипт отмечен галочкой.