ReNamer:Pascal Script:Initialization of variables

From den4b Wiki
Revision as of 17:22, 25 May 2009 by Krtek (talk | contribs) (Created page with '==Initialization of variables== One of the important things to understand when you play with ReNamer is that rules are applied file-by-file, which means you get all the rules ap...')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Initialization of variables

One of the important things to understand when you play with ReNamer is that rules are applied file-by-file, which means you get all the rules applied to the first file and then all the rules (in order as they appear in rules window) applied to the next file and so on.

For PascalScript rules it means that script is run for x times (where x is number of files marked for renaming in the files table). The trick that makes script useful is that it preserves values of variables between executions of the script during one Preview operation (although variables are reset to their default values every time you press Preview or AutoPreview takes place). It means you can rely on any incrementation you let the script to do. The drawback of that situation is that you can’t simply set starting values of variables in the script, because they will be reset to these starting values on every execution of the script (so for every file), eg. this script

var
i : Integer;

begin
  i:=0
  i:=i+1;
  Filename:=IntToStr(i) + '.txt';
end.

will make every filename to be "1.txt".

If we need any initialization of variables we need an ability to write such a code that will be executed only during the first execution of the script. To do that we have to learn one very useful thing: all boolean variables in ReNamer’s PascalScript have their default value set to FALSE. With that knowledge we can write initialization part of the script:

var
  Initialized: Boolean;

procedure Initialize;
begin
  Initialized := True;
  // Initialization code here
end;

begin
  if not Initialized then Initialize;
  // The main renaming code here
end.

Procedure Initialize is executed only if Initialized variable is FALSE. And as the procedure sets the variable Initialized to TRUE, it prevents the initialization code to be executed more than once.

Now we can rewrite the serialization script from previous chapter so it could start eg. from 5.

var
  Initialized: Boolean;
  i : Integer;

procedure Initialize;
begin
  Initialized := True;
  i:=5;
end;

begin
  if not Initialized then Initialize;

  FileName:=IntToStr(i)+'_'+FileName;
  i:=i+1;
end.