TStringList.Move

From Soldat Community Wiki
Revision as of 12:16, 24 August 2013 by Mighty (talk | contribs) (new page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
procedure Move(CurIndex, NewIndex: Integer)
 CurIndex: String index that is supposed to be moved
 NewIndex: Target index

Description

Move moves the string at position CurIndex so it has position NewIndex after the move operation. The object associated to the string is also moved.
CurIndex and NewIndex should be in the range of 0 to Count-1, otherwise an exception occurs.

Warning

NewIndex is not the position in the stringlist before the move operation starts. The move operation
1. removes the string from position CurIndex
2. inserts the string at position NewIndex
This may not lead to the desired result if NewIndex is bigger than CurIndex.
Consider the following example:

...

With MyStrings do
begin
  Clear;
  Add('0');
  Add('1');
  Add('2');
  Add('3');
  Add('4');
  WriteLn(CommaText);
  // 0,1,2,3,4
  Move(1,3);
  WriteLn(CommaText);
  // 0,2,3,1,4
end;

...


Example

Example swaps 2 random elements of the list. It takes care of the case described in Warning section.

Note: this will be done when the server starts, and apparently Random is dependant on soldatserver run time, and thus it will always generate the same pair of numbers in this particular example
var
  s: TStringList;
  i1,i2: integer;

begin
  s := File.CreateStringList();
  s.Append('a');
  s.Append('b');
  s.Append('c');
  s.Append('d');
  s.Append('e');
  
  if s.Count > 1 then // check whether there are at least 2 strings
  begin
    // Generate 2 different indexes
    i1 := Random(0,s.Count-1);
    repeat
      i2 := Random(0,s.Count-1);
    until i1 <> i2;
    // handle the situation described in Warning section
    if i2 > i1+1 then 
      Dec(i2);
    // all set
	
    s.Move(i1,i2);
    // WriteLn('Swapped strings number '+inttostr(i1)+' and '+inttostr(i2)+': '+s.CommaText);
    // uncomment line above to see the effect
  end
  else
    WriteLn('You need at least 2 strings in the list');
  
  s.Free;
end.