Script References

Script-V2.0
Many procedures and functions have been deprecated in Script-V2.0. The new scripting engine is more in "object oriented" style.

The scripting language is an advanced concept which can be used to turn Usine into a very powerful audio, MIDI and data engine. The language is based on the Pascal programming language.

Structure of a script

Init

This procedure is called when the script is compiled or loaded. It's the place where you initialize inlets/outlet or any variable.

procedure Init;
begin
  // Initialisation code
 input := CreateParam('input',ptDatafader,pioInput);
 input.Min(0);
 input.Max(100);
 input.Symbol('%');
 input.DefaultValue(10);
 input.asFloat(10);  
end;

Destroy

This procedure is called when the script is destroyed.

Inlets/outlet are destroyed automatically so you mustn't destroy them in the Destroy bloc.

procedure Destroy;
begin
  MyStringList.free;
  SetLength(MyArray,0);
end;

Process

This procedure is called on each execution bloc (around 3ms with a normal setup). It's the place where you generally do the calculation.

procedure Process;
var inval : single;
begin
  inval := input.asFloat;
  output.asFloat(inval);     
end;

ProcessThread

This procedure is called in a autonomous realtime thread (not int the Audio thread neither in the IDLE thread) every 10ms. It's the place where you generally asynchronous heavy calculations.

this thread is not synchronized to the audio thread and is not suitable for MIDI processing.

procedure ProcessThread;
var inval : single;
begin
  for i:= 1 to NBVALUES 
  do begin
     inval := input[i].asFloat;
     output[i].asFloat(inval);
  end;
end;

ProcessIDLE

This procedure is called at the setup refresh speed (around 25ms or 50ms). It's the place where you do calculation which doesn't need a fast speed, IML or graphic stuffs like SendInternalMsg (see bellow).

procedure ProcessIDLE;
begin
 // do something
end;

Callback

This procedure is called each time an inlet is modified. The N parameter is the index of the modified inlet.

That allows an optimisation over constant running Process procedure: the code will run only if input changed.

The Callback will scan the inputs from 0 to n and can trigg a specific code when input change is detected.

So if results are supposed to be computed only when input changed, prefer the callback to the process procedure.

However if things need computations at a different bloc time that input changed, still need the process procedure.

For exemple an input change can set to 1 a parameter in callback, but if wanna set this param back to 0 next bloc, (like a 'has chg' behavior) the code to set back to 0 will occur in Process Procedure, unless it's trigg by an input.

You can use either Callback or Process Procedure, or booth simultaneously according to your needs.

The callback is provided at messages rate, typically every 25 or 50ms depending on the setup refresh speed.

To ensure a faster callback (immediately after the inlet has been modified) use the FastCallBack procedure describe bellow.

procedure Init;
begin
  // Initialisation of a fast callback inlet
 input := CreateParam('input',ptDatafader,pioInput);
 input.FastCallBack(true);
end;

procedure Callback(N:integer);
var inval : single;
begin
  if n=input
  then begin
    inval := input.asFloat;
    output.asFloat(inval);     
  end;
end;

Example

Usine contains many examples that you can get in the browser-panel tab /Scripts/Examples/.

//GLOBAL VARIABLES AND TPARAMETER  DECLARATIONS
var input  :TParameter;               
var output :TParameter;                   

//PROCESS                 
PROCEDURE PROCESS();
BEGIN   
  output.asFloat(input.asFloat)
END;                  

//INIT PROCEDURE
PROCEDURE INIT();

BEGIN    
 input:=CreateParam('in',ptDataFader,pioInput);
 output:=CreateParam('out',ptDataFader,pioOutput);  
 ModuleColor($FF8E44AD);              
END;                     

//CALLBACK         
PROCEDURE CALLBACK(N:INTEGER);
BEGIN
  CASE N OF
   input: Begin     
          Trace('input has changed')
          End;
  End;          
END;                              

Declarations

Types

// Current execution platform
type TPlatform = (
                  plWindowsIntel,
                  plWindowsARM,
                  plMacOSIntel,
                  plMacOSARM,
                  plLinuxIntel,
                  plLinuxARM,
                  plIOSARM,
                  plAndroidARM
                  );
type TParameter = int32;
type TAlphaColor= uint32;
type TScale     = (
                  lsLinear,
                  lsLog,
                  lsExp
                  );
type TParamType = (
                     ptTextField,     // text in/outlet
                     ptColor,         // color in/outlet
                     ptMIDI,          // MIDI in/outlet
                     ptGainFader,     // gain fader -84 to +12 dB in/outlet
                     ptAudio,         // audio in/outlet
                     ptDataField,     // float or integer in/outlet without mouse fader (click to edit value)
                     ptDataFader,     // float or integer in/outlet with mouse fader (use the mouse to modify)
                     ptButton,        // button (trigger) in/outlet
                     ptListBox,       // combobox box in/outlet use SetListBoxString to set items
                     ptSwitch,        // switch in/outlet
                     ptArray,         // array in/outlet
                     ptIpAddress,     // data with the format xxx.xxx.xxx.xxx in/outlet suitable for IP addresses
                     ptSmpte,         // data with the format  HH:MM:SS:FF in/outlet suitable for SMPTE
                     ptMIDINoteFader, // midi note in the range 0..127 displayed as MIDI notes ie. 36-C1
                     ptPointerBitMap, // general bitmap pointer in/outlet in hexadecimal
                     ptPointer,       // general pointer in/outlet in hexadecimal
                     ptLed,           // equivalent to ptSwitch with a left led layout
                     ptChooseFolder,  // open folder in/outlet
                     ptRightLed,      // equivalent to ptSwitch with a right left led layout
                     ptTriggerLed,    // equivalent to ptSwitch with a left led type layout 
                     ptFileName       // open a file name in/outlet
                     ptBitwise        // bitwise in/outlet
                     );

type  TParamIOType = (
                   pioInput,          // the parameter is an inlet
                   pioOutput,         // the parameter is an outlet
                   pioBoth,           // the parameter is an inlet and outlet
                   pioNone            // the parameter is not visible in the module
                   ); 

type  TMIDI        = Record
                   Msg   : Byte;
                   Data1 : Byte;
                   Data2 : Byte;
                   Channel : byte;
                   end;

Constants

BlocSize      (integer)   // size of Usine audio blocs typically 128, see setup/audio
BlocDuration  (float)     // duration of a bloc calculation according to the sampling rate 
                          // and bloc size, typically 2.9 ms
RefreshSpeed  (integer)   // refresh speed in ms as defined in the setup, typically 25ms
SamplingRate  (float)     // current audio sampling rate, typically 44100

PLATFORM      (TPlatform) // platform, see TPlatform above

Create Parameters

Parameters must be created in the Init procedure.

// Create a new parameter, 
// returns the parameter's number
function CreateParam    (caption: string; typ: TParamType, ioTyp : TParamIOType ):TParameter; 

procedure TParameter.IsInput   (val: boolean);      // set to true if the parameter has input port
procedure TParameter.IsOutput  (val: boolean);      // set to true if the parameter has output port
procedure TParameter.Scale     (val: TScale);       // set the scale, if the param is a fader
procedure TParameter.Color     (val: TAlphaColor);  // set the front color of the fader or ON Color for switches
procedure TParameter.OffColor  (val: TAlphaColor);  // set the off color only for switches parameters
procedure TParameter.Visible   (val: Boolean);      // determines if the parameter is visible, true by default
procedure TParameter.Min       (val: single);       // set min parameter value
procedure TParameter.Max       (val: single);       // set max parameter value
procedure TParameter.MinMaxNoLimit(val : boolean);  // when set to TRUE the parameter's bounds are not limited 
                                                    // by min/max

procedure TParameter.DefaultValue  (val: single);   // set default param value, when created
procedure TParameter.Caption       (val: string);   // set or change displayed caption 
procedure TParameter.Symbol        (val: string);   // set displayed symbol ie. 'ms','%'
procedure TParameter.Format        (val: string);   // set format string of the displayed value 
                                                    // ie. '%g','%.0f','%.1f'
procedure TParameter.ListBoxString (val: string);   // set listbox items commaText ie.'"item1","item2"'
procedure TParameter.ReadOnly      (val: boolean);  // set to TRUE if the user can't modify value
procedure TParameter.FastCallBack  (val: boolean);  // set to TRUE to use a fast callback instead of the
                                                    // normal queue processing  (25-50 ms)
procedure TParameter.DontSave      (val: boolean);  // specifies if the parameter need to be save 
                                                    // in the patch or not
procedure TParameter.SavedName     (val: string);   // set name which will be used to store the value
                                                    // by default value are stored according 
                                                    // their caption
procedure TParameter.IsSeparator   (val: boolean);  // determines if the parameter is preceded by a 
                                                    // blank line in the module's panel

Example of parameters creation

///////////////////////////////////////////////////////////////////
// example of parameters creation
///////////////////////////////////////////////////////////////////
var  pInput, pOutOrder, pMono, pMaxOut : tParameter;
var  pOutput : ARRAY[1..NUM_OUTPUTS] of tParameter;  

procedure init;
var i : Integer;
begin 
   pInput := CreateParam('midi in', ptMidi, pioInput); 

   pOutOrder := CreateParam('out order', ptListBox,pioInput);
   pOutOrder.ListBoxString('"round robin","from first","random","rnd no repeat"');
   outOrder := roundRobin;

   pMono := CreateParam('monophonic', ptSwitch,pioInput); 

   pMaxOut := CreateParam('max out used', ptDataFader,pioInput); 
   pMaxOut.Min(1); 
   pMaxOut.Max(NUM_OUTPUTS); 
   pMaxOut.asInteger(NUM_OUTPUTS);
   pMaxOut.Format('%.0f');

   for i := 1 TO NUM_OUTPUTS do 
   begin
      pOutput[i] := CreateParam('midi out ' + inttostr(i), ptMidi,pioOutput);
   end;      
end;

Access to parameter's Value

float (single) values

procedure TParameter.asFloat(val : single);                       // set the value of a float parameter
function TParameter.asFloat:single;                               // get the value of a float parameter

//example
output.asFloat(sin(input.asFloat));

integer values

procedure TParameter.asInteger(val : integer);               // set the value of an integer parameter
function TParameter.asInteger:integer;                       // get the value of a integer parameter

//example
if listbox.asInteger=-1 
then listbox.asInteger(1);

string values

procedure TParameter.asString(val : string);                 // set the value of a string parameter
function TParameter.asString:string;                         // get the value of a string parameter

//example
if textfield.asString='' 
then textfield.asString('default value string');

MIDI values

procedure TParameter.asMidi(index : integer; val : TMIDI);       // set the value of a MIDI parameter at the index
function TParameter.asMidi(index : integer):TMIDI;               // get the value of a MIDI parameter at the index

nbOfMidi := input.Length;  // get the number of incoming midi codes  
output.length(nbOfMidi);

if nbOfMidi > 0 
then begin           
   transpoVal := trunc(transpo.asInteger); // get the transpo value    

   for i := 0 to nbOfMidi-1         // loop for all input codes, for polyphonic data (chords)
   do begin
     ReceivedMidi := input.asMidi(i); // get each code
     ReceivedMidi.data1 := ReceivedMidi.data1+transpoVal; // calculate transpo
     output.asMidi(i,ReceivedMidi); // set output value     
   end;
end 

Array values

procedure TParameter.asArray(index : integer; val : single);          // set the value of a float array parameter at the index
function TParameter.asArray(index : integer):single;                  // get the value of a float array parameter at the index

SL1.Create;      
L:= arrayIn.Length;     
For i:= 0 to L-1                                                    
do begin                                   
      s := ArrayIn.asArray(i);                
      SL1.add(FloatToStr(s)); 
end;                          
CommaOut.asString(SL1.GetCommatext);  
SL1.Free

Colors values

procedure TParameter.asColor(val : TAlphaColor); // set the value of a color parameter
function TParameter.asColor:TAlphaColor;         // get the value of a color parameter

col := colorIn.asColor;      
// complementary color
col.R(255-col.R);
col.G(255-col.G);
col.B(255-col.B);
colorOut.asColor(col);

BitWise values

procedure TParameter.asBitWise(val : uInt32); // set the value of a bitwise parameter
function TParameter.asBitWise:uInt32;         // get the value of a bitwise parameter

bit := BitWiseIn.asBitWise;      
bit := bit and $0FFFFFFF;
BitWiseOut.asBitWise(bit);

Pointer

function TParameter.asPointer:pfloat;                              // returns true if a parameter's value equal 1

Returns the pointer (pfloat) to the value of the parameter or to the first value of the array (is the parameter is an array). if the length() of the parameter is zero, it returns nil.

Get the length of a values (number of elements)

procedure TParameter.Length(l : integer);                        // set le length of a parameter
function TParameter.Length:integer;                              // get the length of a parameter

L:= arrayIn.Length;     
For i:= 0 to L-1                                                    
do begin                                   
      s := ArrayIn.asArray(i);                
      trace(s); 
end;                          

various boolean functions

function TParameter.equal1:boolean;                              // returns true if a parameter's value equal 1
function TParameter.equal0:boolean;                              // returns true if a parameter's value equal 0

if switch.equal1
then trace('on');
if switch.equal0
then trace('off');

Global functions and procedures

Trace Values

To display information's in the trace-panel.

procedure Trace(S:string; Value:variant);  
procedure Trace(S:string);  
procedure Trace(I:Integer); 
procedure Trace(F:single);  

Module color

Procedure ModuleColor(Color:TAlphaColor);    // set the color of the module
                                             // as it is displayed in the patch

Example of module's color (red and blue) inside a patch.

SMPTE and Markers Position.

function GetSmptePos:double;
procedure SetSmptePos (pos:double);
function GetLoopMarkerPos (N:integer):double; // N from 0 to nbMarkers-1

Dynamic Array's or String Length Manipulation

function getarraylength (arr :array: integer;
procedure setarraylength(arr :array; len:integer);

Usine Internal Messages (IML)

SendUsineMsg(msg:string); 
SendUsineMsg(msg,arg1:string);
SendUsineMsg(msg,arg1,arg2:string);
SendUsineMsg(msg,arg1,arg2,arg3:string);
SendUsineMsg(msg,arg1,arg2,arg3,arg4:string);   
SendUsineMsg(msg,arg1,arg2,arg3,arg4,arg6:string);

function GetVariableString(name:string):string;
function GetVariableInteger(name:string):integer;
function GetVariableFloat(name:string):double;

The SendInternalMsg script command should not be executed in the process procedure context.

You can use safely it in the processIDLE procedure. In the callback procedure set SetFastCallBack(false); to asynchronously execute the callback function that contains the SendUsineMsg calls in the Usine IDLE processing thread instead of the process thread. Otherwise IML calls might lead to undefined behavior (function might not be executed, Usine crashes, etc.)

// example
SendInternalMsg2('SET-TARGET-PATCH','SENDER-PATCH');
SendInternalMsg4 ('GET-VALUE',GetStringValue(Input1),GetStringValue(Input2),'THEPARAMVALUE');
SendInternalMsg3 ('SET-VALUE','PARAM','1','THEPARAMVALUE');
SendInternalMsg4('SET-VALUE',GetStringValue(Input1),GetStringValue(Input2),FloatTostr(GetValue(Input3)));

StringList

  function TStringList.create:TStringList; 
  function TStringList.GetCommaText:String;
  procedure TStringList.SetCommaText(Comma:string);
  procedure TStringList.Sort;
  procedure TStringList.SortDesc;
  procedure TStringList.SaveToFile(FileName:string);   // If no path is specified for the file; will default to the last location saved/opened in Usine. 
  procedure TStringList.LoadFromFile(FileName:string); // If no path is specified for the file; will default to the last location saved/opened in Usine.
  procedure TStringList.clear;
  procedure TStringList.free;
  function TStringList.getstrings(index:integer):String;
  procedure TStringList.setstrings(index:integer;value:String);
  procedure TStringList.add(value:String);
  procedure TStringList.delete(index:integer);  // Deletes the string at the index
  procedure TStringList.delete(value:integer);  // Deletes the value if it exists
  function TStringList.indexOf(value:string):integer;
  function TStringList.count:integer;
  function TStringList.Getcount:integer;
// example
procedure ReadTextFile;
begin
  st.create;              
  st.clear;          
  st.loadfromFile(fname.asString);
  textOut.asString(st.GetCommaText);
  st.free;          
end;  

// example
procedure SaveToTextFile;
begin                    
  st.create;                          
  st.setcommaText(input.asString);    
  st.SaveToFile(folder.asString+pathdelim+fname.asString);
  st.free;       
end;    

// example
st.create;      
L:= arrayIn.Length;     
For i:= 0 to L-1                                                    
do begin                                   
  s := ArrayIn.asArray(i);                
  SL1.add(FloatToStr(s)); 
end;                          
CommaOut.asString(SL1.GetCommatext);   
st.free;

Math functions

  Function minS(const A,B:single):Single;
  Function MaxS(const A,B: Single): Single;
  Function maxI(const A,B:integer):integer;
  Function minI(const A,B:integer):integer;

  Function Pi   : Extended;
  Function Log  (e: Extended) : Extended;
  Function Exp  (e: Extended) : Extended;) : Extended;
  Function Arctan   (e: Extended) : Extended;
  Function Arcsin   (e: Extended) : Extended;
  Function Arccos   (e: Extended) : Extended;
  function Abs(d: Extended): Extended;
  function Abs(d: Int64): Int64;
  function Power(Base, Exponent: Extended): Extended;
  function Sqr(d: Extended): Extended;
  function Sqrt(d: Extended): Extended;
  function ArcTan(d: Extended): Extended;
  function Ln(d: Extended): Extended;
  function Sin(d: Extended): Extended;
  function Cos(d: Extended): Extended;
  function Exp(d: Extended): Extended;
  function Round(d: Extended): Int64;
  function Round(d: Extended; Precision: Int8): Extended;
  function Frac(d: Extended): Extended;
  function Int(d: Extended): Extended;
  function Trunc(d: Extended): Int64;
  function Ceil(d: Extended): Int64;
  function Floor(d: Extended): Int64;

  function Random(Min, Max: Int64): Int64;
  function Random(l: Int64): Int64;
  function Random: Extended;
  procedure Randomize;

Date and Time functions


var
  HoursPerDay,
  MinsPerHour,
  SecsPerMin,
  MSecsPerSec,
  MinsPerDay,
  SecsPerDay,
  MSecsPerDay,
  DateDelta;

type
  TDateTime : double;
  TTime : double;

  function EncodeDate(Year, Month, Day: UInt16): TDateTime;
  function EncodeTime(Hour, Min, Sec, MSec: UInt16): TDateTime;
  procedure DecodeDate(DateTime: TDateTime; var Year, Month, Day: UInt16);
  function DecodeDateFully(DateTime: TDateTime; var Year, Month, Day, DOW: UInt16): Boolean;
  procedure DecodeTime(DateTime: TDateTime; var Hour, Min, Sec, MSec: UInt16);

  function Date: TDateTime;
  function Time: TDateTime;
  function Now: TDateTime;

  function GetTickCount: UInt32;
  procedure Sleep(MilliSeconds: UInt32);

  procedure ReplaceTime(var DateTime: TDateTime; NewTime: TDateTime);
  procedure ReplaceDate(var DateTime: TDateTime; NewDate: TDateTime);
  function DateTimeInRange(ADateTime: TDateTime; AStartDateTime, AEndDateTime: TDateTime): Boolean;
  function FormatDateTime(Format: string; DateTime: TDateTime): string;
  function StrToDate(s: string): TDateTime;
  function StrToDateDef(s: string; Default: TDateTime): TDateTime;
  function StrToTime(s: string): TDateTime;
  function StrToTimeDef(s: string; Default: TDateTime): TDateTime;
  function StrToDateTime(s: string): TDateTime;
  function StrToDateTimeDef(s: string; Default: TDateTime): TDateTime;

Files

  function  GetApplicationPath:string; //give the absolute path of the current Usine's folder

  procedure FindFiles(const Directory: String; Extensions: String; Recursive: Boolean; Result: TStringList); // [Extensions] can be a comma-text like 'pat,wkp'
  procedure FindDirectories(const Directory: String; Recursive: Boolean; Result: TStringList); 
  function WriteFileContents(const FileName: String; const Text: String; Append: Boolean): Boolean;
  function ReadFileContents(const FileName: String): String;
  function CreateDirectory(const Directory: String): Boolean;
  function ForceDirectories(const Directory: String): Boolean;
  function DeleteDirectory(const Directory: String; OnlyChildren: Boolean): Boolean;
  function DeleteFile(const FileName: String): Boolean;
  function RenameFile(const OldFileName, NewFileName: String): Boolean;
  function CopyFile(const SourceFileName, DestFileName: String; Overwrite: Boolean = False): Boolean;
  function FileExists(const FileName: String): Boolean;
  function DirectoryExists(const Directory: String): Boolean;
  function FileAge(const FileName: String): Int32; overload;
  function FileAge(const FileName: String; out FileDateTime: TDateTime): Boolean; overload;
  function ExtractFilePath(const FileName: String): String;
  function ExtractFileDrive(const FileName: String): String;
  function ExtractFileName(const FileName: String): String;
  function ExtractFileExt(const FileName: String): String;
  function ExtractFileDir(const FileName: String): String;
  function ExpandFileName(const FileName: String): String;
  function ExtractRelativePath(const BaseName, DestName: String): String;
  function IncludeTrailingPathDelimiter(const Path: String) : String;
  function ExcludeTrailingPathDelimiter(const Path: String): String;
  function IncludeTrailingBackslash(const Path: String) : String;
  function ExcludeTrailingBackslash(const Path: String): String;
  function IncludeLeadingPathDelimiter(const Path : String) : String;
  function ExcludeLeadingPathDelimiter(const Path: String): String;

  // for compatibility
  function  SubFileExt(filename:String):string;
  function  PathDelim:string; // returns '/' on MACOS, '\' on windows
  procedure CreateDir(dir:String);

Strings functions

  type TTextLineBreakStyle  = (tlbsLF, tlbsCRLF, tlbsCR);
  type TReplaceFlags = set of (rfReplaceAll, rfIgnoreCase);

  function UpperCase(s: string): string;;
  function LowerCase(s: string): string;
  function UpCase(c: AnsiChar): AnsiChar;
  function UpCase(c: WideChar): WideChar;

  function CompareStr(s1, s2: string): Int32;
  function CompareMem(p1, p2: Pointer; Length: PtrUInt): EvalBool;
  function CompareText(s1, s2: string): Int32;
  function SameText(s1, s2: string): EvalBool;

  function  Copy (s: string; ifrom, icount: Longint): string;
  procedure Delete(var s: string; ifrom, icount: Longint);
  procedure Insert(s: string; var s2: string; ipos: Longint): string;
  function  StrGet(var S : String; i : Integer) : Char;
  procedure StrSet(c: Char; I : Integer; var s : String);
  function  Length(s: String) : Longint; 
  procedure SetLength(var S: String; L: Longint); 

  function AnsiUpperCase(s: string): string;
  function AnsiLowerCase(s: string): string;
  function AnsiCompareStr(s1, s2: string): Int32;
  function AnsiCompareText(s1, s2: string): Int32;
  function AnsiSameText(s1,s2:String): EvalBool;
  function AnsiSameStr(s1,s2:String): EvalBool;

  function Trim(s: string): string;
  function TrimLeft(s: string): string;
  function TrimRight(s: string): string;
  function PadL(s: string; Len: SizeInt; c: Char = '' ''): string;
  function PadR(s: string; Len: SizeInt; c: Char = '' ''): string;
  function Padz (s: string;I : longInt) : string; //  Is similar to Padl, but adds zeroes instead of spaces
  function QuotedStr(s: string): string;
  function AnsiQuotedStr(s: string; Quote: Char): string;
  function AnsiDequotedStr(s: string; AQuote: Char): string;

  function WrapText(Line, BreakStr: string; BreakChars: set of AnsiChar; MaxCol: Int32): string;
  function AdjustLineBreaks(s: string; Style: TTextLineBreakStyle): string;

  function IntToHex(Value: Int64; Digits: Int32 = 1): string;
  function IntToHex(Value: UInt64; Digits: Int32 = 1): string;
  function IntToStr(i: Int64): string; overload;
  function IntToStr(i: UInt64): string;
  function StrToInt(s: string): Int32;
  function StrToIntDef(s: string; Def: Int32): Int32;
  function StrToInt64(s: string): Int64;
  function StrToInt64Def(s: string; Def: Int64): Int64;
  function StrToUInt64(s: string): UInt64;
  function StrToUInt64Def(s: string; Def: UInt64): UInt64;
  function FloatToStr(f: Extended): string;
  function StrToFloat(s: string): Extended;
  function StrToFloatDef(s: string; Def: Extended): Extended;
  function CurrToStr(Value: Currency): string;
  function StrToCurr(s: string): Currency;
  function StrToCurrDef(s: string; Def: Currency): Currency;
  function StrToBool(s: string): EvalBool;
  function BoolToStr(B: EvalBool; TrueS: string = ''True''; FalseS: string = ''False''): string;
  function StrToBoolDef(s: string; Default: EvalBool): EvalBool;

  function Format(Fmt: string; Args: array of Variant): string;
  function FormatFloat(Format: string; Value: Extended): string;
  function FormatCurr(Format: string; Value: Currency): string;

  function LastDelimiter(Delimiters, s: string): SizeInt;
  function StringReplace(S, OldPattern, NewPattern: string; Flags: TReplaceFlags): string;
  Function IsDelimiter(Delimiters, s: string; Index: SizeInt): EvalBool;

  function Pos(Substr: string; Source: string): SizeInt;
  function StringOfChar(c: Char; l: SizeInt): string;
  function Replicate(c: char; I : longInt) : string; // Builds a string containing i times the character c

String Helpers

  function string.startswith ( AValue:string ) : boolean;
  function string.endswith   ( AValue:string ) : boolean;

Windows registry

WINDOWS only

  procedure WriteRegistryInteger(AKey, AName:string; AValue:integer);
  procedure WriteRegistryString (AKey, AName:string; AValue:string);
  function ReadRegistryInteger  (AKey, AName:string) : integer;
  function ReadRegistryString   (AKey, AName:string) : string;

Variants

  type TVarType = Word;

  {------------------------------------------------------------
  The variant types are described in the following table: 
  varEmpty  The variant is Unassigned.  
  varNull  The variant is Null.  
  varAny  Represents a Variant that can hold any value.  
  varSmallint  16-bit signed integer (type Smallint in Delphi, short in C++).  
  varInteger  32-bit signed integer (type Integer in Delphi, int in C++).  
  varSingle  Single-precision floating-point value (type Single in Delphi, float in C++).  
  varDouble  Double-precision floating-point value (type double).  
  varCurrency  Currency floating-point value (type Currency).  
  varDate  Date and time value (type TDateTime).  
  varOleStr  Reference to a dynamically allocated UNICODE string.  
  varDispatch  Reference to an Automation object (an IDispatch interface pointer).  
  varError  Operating system error code.  
  varBoolean  16-bit Boolean (type WordBool).  
  varVariant  Indicates another variant.  
  varUnknown  Reference to an unknown object (an IInterface or IUnknown interface pointer).  
  varShortInt  8-bit signed integer (type ShortInt in Delphi or signed char in C++).  
  varByte  A Byte.  
  varWord  Unsigned 16-bit value (Word).  
  varLongWord  Unsigned 32-bit value (type LongWord in Delphi or unsigned long in C++).  
  varInt64  64-bit signed integer (Int64 in Delphi or __int64 in C++).  
  varStrArg  COM-compatible string.  
  varString  Reference to a dynamically allocated string (not COM-compatible).  
  varArray  Indicates a Variant array.  
  varByRef  Indicates that the variant contains a reference as opposed to a value.  
  varTypeMask  Indicates the type of each array element. 
  -----------------------------------------------------------------}

  type HResult = Integer;
  {-----------------------------------------------------------------
  // possible values of HRESULT
  S_OK = 0                    // No error. In some APIs, S_OK indicates a successful operation with a return value of True. 
  S_FALSE = $00000001        // No error, but the operation did not produce a useful result. In some APIs, S_FALSE indicates a successful operation with a return value of False.  
  E_NOINTERFACE = $80004002 // Interface not supported. 
  E_UNEXPECTED = $8000FFFF  // Catastrophic failure. 
  E_NOTIMPL = $80004001     // Operation not implemented. 
  -----------------------------------------------------------------}

  Type TVariantRelationship = (vrEqual, vrLessThan, vrGreaterThan, vrNotEqual);

  function VarType(const V: Variant): TVarType;
  function VarAsType(const V: Variant; aVarType: TVarType): Variant;
  function VarIsByRef(const V: Variant): EvalBool;
  function VarIsEmpty(const V: Variant): EvalBool;
  function VarIsNull(const V: Variant): EvalBool;
  function VarIsClear(const V: Variant): EvalBool;

  function VarIsError(const V: Variant; out AResult: HRESULT): EvalBool;
  function VarAsError(AResult: HRESULT): Variant;

  function VarIsCustom(const V: Variant): EvalBool;
  function VarIsOrdinal(const V: Variant): EvalBool;
  function VarIsFloat(const V: Variant): EvalBool;
  function VarIsNumeric(const V: Variant): EvalBool;
  function VarIsStr(const V: Variant): EvalBool;
  function VarIsArray(const A: Variant; AResolveByRef: EvalBool = True): EvalBool;

  function VarToStr(const V: Variant): string;
  function VarToStrDef(const V: Variant; ADefault: string): string;
  function VarToWideStr(const V: Variant): WideString;
  function VarToWideStrDef(const V: Variant; ADefault: WideString): WideString;
  function VarToUnicodeStr(const V: Variant): UnicodeString;
  function VarToUnicodeStrDef(const V: Variant; ADefault: UnicodeString): UnicodeString;
  function VarToDateTime(const V: Variant): TDateTime;
  function VarFromDateTime(DateTime: TDateTime): Variant;

  function VarInRange(const AValue, AMin, AMax: Variant): EvalBool;
  function VarEnsureRange(const AValue, AMin, AMax: Variant): Variant;
  function VarSameValue(const A, B: Variant): EvalBool;
  function VarCompareValue(const A, B: Variant): TVariantRelationship;

  function VarTypeIsValidArrayType(aVarType: TVarType): EvalBool;
  function VarTypeIsValidElementType(aVarType: TVarType): EvalBool;

  function VarArrayCreate(Bounds: array of SizeInt; aVarType: TVarType): Variant;
  function VarArrayOf(Values: array of Variant): Variant;
  procedure VarArrayRedim(var A: Variant; HighBound: SizeInt);

  function VarArrayAsPSafeArray(const A: Variant): Pointer;
  procedure VarCopyNoInd(var Dest: Variant; const Source: Variant);

  function VarArrayDimCount(const A: Variant): SizeInt;
  function VarArrayLowBound(const A: Variant; Dim: SizeInt): SizeInt;
  function VarArrayHighBound(const A: Variant; Dim: SizeInt): SizeInt;

  function VarArrayLock(const A: Variant): Pointer;
  procedure VarArrayUnlock(const A: Variant);
  function VarArrayRef(const A: Variant): Variant;

  function VarArrayGet(const A: Variant; Indices: array of Int32): Variant;
  procedure VarArraySet(var A: Variant; const Value: Variant; Indices: array of Int32);

See also

More examples

version 5.2.221206

Edit All Pages