Search code examples
delphidelphi-7

I am getting an "undeclared identifier" error in Delphi and I don't know why?


I am having troubles and am unsure as to why i am getting an "Undeclared Identifier" error in the following code:

procedure getword;
var
  i: integer;
begin
  randomize;
  randomwordnumber := random (20) + 1;
  randomword := wordlist [randomwordnumber];
  for i:=1 to length(randomword) do word:= word + '?';
  lblrandomword.Caption := (word);
end;

Also here is the exact error code:

[Error] Unit1.pas(138): Undeclared identifier: 'lblrandomword'

Thank-You in advance!


Solution

  • We can only guess but lblrandomword probably is a TLabel on a form. You have to make getword a method of that form. Maybe like this:

      TForm1 = class(TForm)
        lblrandomword: TLabel;
        //...
      private
        procedure getword;
        //...
      end;
    
    procedure TForm1.getword;
    var
      i: integer;
    begin
      randomize;
      randomwordnumber := random(20) + 1;
      randomword := wordlist[randomwordnumber];
      for i := 1 to length(randomword) do word := word + '?';
      lblrandomword.Caption := (word);
    end;
    

    Alternatively, you can pass the label to getword as a parameter (courtesy of Sebastian Proske).

    Additional note: If there are no error messages regarding randomwordnumber and so on, these are probably global variables. This is generally considered bad practice.