Difference between revisions of "Constructor"

From Soldat Community Wiki
Jump to: navigation, search
(new page)
 
m (Usage)
 
(2 intermediate revisions by the same user not shown)
Line 10: Line 10:
  
 
<syntaxhighlight lang="pascal">
 
<syntaxhighlight lang="pascal">
 +
var
 +
  i: integer;
 +
 
procedure SpawnMedkit(posx,posy: single);
 
procedure SpawnMedkit(posx,posy: single);
 
var temp: TNewMapObject;
 
var temp: TNewMapObject;
 
begin
 
begin
   temp := TNewMapObject.Create;
+
   temp := TNewMapObject.Create; // constructor
 
   temp.X := posx;
 
   temp.X := posx;
 
   temp.Y := posy;
 
   temp.Y := posy;
 
   temp.Style := 16;
 
   temp.Style := 16;
   Map.AddObject(temp); // we could also save object's ID (newly spawned medkit)\
+
   Map.AddObject(temp); // we could also save object's ID (newly spawned medkit)
   temp.Free; // IMPORTANT!
+
   temp.Free; // IMPORTANT! destructor
 
end;
 
end;
  
 
procedure MyOnSpeak(p: TActivePlayer; Text: string);
 
procedure MyOnSpeak(p: TActivePlayer; Text: string);
 
begin
 
begin
   if lowercase(Text) = 'Medic!' then
+
   if Text = 'Medic!' then
 
     SpawnMedkit(p.X,p.Y);
 
     SpawnMedkit(p.X,p.Y);
 
end;
 
end;
 +
 +
begin
 +
  for i:=1 to 32 do
 +
    Players[i].OnSpeak := @MyOnSpeak;
 +
end.
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 11:43, 22 August 2013

Description

Constructors are used to allocate memory for a new object/class/variable etc.
It's important to remember to free previously allocated memory by using Destructors

Usage

There are some user constructable classes in Script Core 3, for example TNewPlayer and TNewMapObject.
Below example shows the usage of TNewMapObject.Create, which is this classes constructor.

var
  i: integer;

procedure SpawnMedkit(posx,posy: single);
var temp: TNewMapObject;
begin
  temp := TNewMapObject.Create; // constructor
  temp.X := posx;
  temp.Y := posy;
  temp.Style := 16;
  Map.AddObject(temp); // we could also save object's ID (newly spawned medkit)
  temp.Free; // IMPORTANT! destructor
end;

procedure MyOnSpeak(p: TActivePlayer; Text: string);
begin
  if Text = 'Medic!' then
    SpawnMedkit(p.X,p.Y);
end;

begin
  for i:=1 to 32 do
    Players[i].OnSpeak := @MyOnSpeak;
end.