I’ve got the following code in Form1.
public
{ Public declarations }
cas: integer;
end;
Then I work with the variable, and then I call another form with Form2.ShowModal; On Form2 I try to execute the following: Label9.Caption:=Format('%ds',[Form1.cas]);. But no matter what I do, in Form1 ‘cas’ is assigned the proper value but in Form2 it always shows “0s”. Why does that happen?
EDIT:
Now I have in the first unit called ‘kolecka’ this
var
Form1: TForm1;
barvy: array[1..6] of TColor;
kola: array[1..22] of TShape;
valid: integer;
bezi: boolean;
presnost: real;
skore: integer;
chyb: integer;
kliku: integer;
cas: integer;
and this in the other unit called ‘dialog’:
implementation
uses
kolecka;
{$R *.dfm}
procedure Statistiky();
begin
With Form2 do begin
Label8.Caption:=IntToStr(kolecka.skore);
Label9.Caption:=Format('%ds',[kolecka.cas]);
Label10.Caption:=IntToStr(kolecka.cas);
Label11.Caption:=IntToStr(skore);
Label12.Caption:=Format('%.2f%%',[presnost]);
end;
end;
But it still doesn’t work.. still shows a zero.
EDIT2:
I feel like every answer says something different and I’m very confused..
EDIT3: This is how ‘cas’ is manipulated in Form1
procedure TForm1.Timer3Timer(Sender: TObject);
begin
cas:=cas+1;
Form1.Label5.Caption:=IntToStr(cas);
end;
FOUND IT!
Meh. I figured out where was the problem.
I was assigning the label captions on Form2 Create and not Show, so of course they were at 0 >.>
In your original question, you declared a field in an object, and you thought it was a global, perhaps?
Notice where you put globals above. Global variables are not fields inside a class. Where you put something, when you write code is called “the context you are in”. Inside a class declaration, something like
publicmakes sense as a visiblity specifier. It does not make things global, it makes them visible to users of the class.To access the global, access it as unitName.VariableName, and don’t forget to add ‘Uses unitName’ to the other unit.
Update You are now correctly accessing the global variable, and it doesn’t contain the value you expected. That’s where we start debugging. Set a breakpoint on the place where you set the variable, and on any other place where it is changed back to 0. Now set a breakpoint on the place where you read the variable. I find that variable writes work better when they actually happen, and when they aren’t over-written by a subsequent write to the same place, that contains a different value. Variables are like a box which contains a number. Zero things writing to it (the code you thought got called did not get called) or two things writing to it (the thing you think should be there but is not there because the second write zapped the first value) are common sources of your sort of confusion.