Search code examples
delphivariableslocalinstancesdelphi-units

Delphi Unit local variables - how to make each instance unique?


In the unit below I have a variable declared in the IMPLEMENTATION section - local to the unit. I also have a procedure, declared in the TYPE section which takes an argument and assigns that argument to the local variable in question. Each instance of this TFrame gets passed a unique variable via passMeTheVar.

What I want it to do is for each instance of the frame to keep its own version of that variable, different from the others, and use that to define how it operates. What seems to be happening, however, is that all instances are using the same value, even if I explicitly pass each instance a different variable.

ie:

Unit FlexibleUnit;
interface
uses
//the uses stuff
type
TFlexibleUnit=class(TFrame)
   //declarations including
   procedure makeThisInstanceX(passMeTheVar:integer);
private
//
public
//
end;

implementation
uses //the uses
var myLocalVar;

procedure makeThisInstanceX(passMeTheVar:integer);
begin
myLocalVar:=passMeTheVar;
end;

//other procedures using myLocalVar 
//etc to the 
end;

Now somewhere in another Form I've dropped this Frame onto the Design pane, sometimes two of these frames on one Form, and have it declared in the proper places, etc. Each is unique in that :

ThisFlexibleUnit : TFlexibleUnit;
ThatFlexibleUnit : TFlexibleUnit;

and when I do a:

ThisFlexibleUnit.makeThisInstanceX(var1); //want to behave in way "var1"
ThatFlexibleUnit.makeThisInstanceX(var2); //want to behave in way "var2"

it seems that they both share the same variable "myLocalVar".

Am I doing this wrong, in principle? If this is the correct method then it's a matter of debugging what I have (which is too huge to post) but if this is not correct in principle then is there a way to do what I am suggesting?

EDIT:

Ok, so the lesson learned here is that the class definition is just that. Many classes can go in one unit and all instances of all classes in the Type section share the implementation section of the unit.


Solution

  • myLocalVar is a global variable, but only visible within the unit.

    A local variable would be in a procedure/function, like

    procedure makeThisInstanceX(passMeTheVar: integer);
    var
      myLocalVar: Integer;
    begin
      myLocalVar := passMeTheVar;
    end;
    

    if you want an instance variable, that is each frame has its own copy, put it in the class:

    type
      TFlexibleUnit = class(TFrame)
         procedure makeThisInstanceX(passMeTheVar:integer);
      private
        myLocalVar: Integer;
      ...
      end;