TStringList in an array in Lazarus - arrays

I have a problem with TStringLists in Lazarus. I have an array called 'trans' of records called 'TTrans' which contain, among other things, TStringList called 'meebetalers'. So when I need to know for example the amount of lines in that StringList I would have to write this right?
trans[i].meebetalers.Count;
Anyways, I first create a stringlist and put the selected strings from a checklistbox in it, and that works (i.e. the program returns 3 when I ask for the Count, which is correct).
In this piece of code I add values to the StringList:
slmeebetalers := TStringList.Create;
for i:= 0 to Form6.CLBox.Count-1 do begin
if Form6.CLBox.Checked[i] then begin
slmeebetalers.Add(Form6.CLBox.Items[i]);
end;
end;
Then I put the stringlist a procedure, and in that procedure I assign my first created StringList to the stringlist I mentionned before (trans[i].meebetalers), see my piece of code next.
Unit6.VoegTransToe(Form6.TransNaam.Text,
Form6.TrComboBox.Text,
bedrag,
slmeebetalers,
Form6.CalendarDialog1.Date);
But when I then ask for the count, it returns 0.
procedure VoegTransToe(naam, betaalpers: string; bedrag: currency;
meebetalers: TStringList; datum: TDateTime);
begin
aantaltrans:= aantaltrans+1;
trans[aantaltrans].naam:=naam;
trans[aantaltrans].pers.naam:=betaalpers;
trans[aantaltrans].bedrag:=bedrag;
trans[aantaltrans].datum:=datum;
meebetalers:= TStringList.Create;
trans[aantaltrans].meebetalers:= TStringList.Create;
trans[aantaltrans].meebetalers.Assign(meebetalers);
meebetalers.Free;
//trans[aantaltrans].meebetalers.Free;
end;
note The difference in name of the variable is because they are in different units
With this code I don't get an error, but it returns 0. When I say //meebetalers.Free; the same happens.
But when I add //trans[aantaltrans].meebetalers.Free; I don't get an error while compiling, but when I call the procedure. Then I get this error:
Project project1 raised exception class 'External: SIGSEGV'.
I think there is something wrong with the Create and Free function, but I don't know what. When I implement the try...finally...end it returns the same error. Can anybody help me?

The problem is that your VoegTransToe() procedure is ignoring the populated TStringList object that is passed in via its meebetalers parameter. You are resetting meebetalers to point at a newly created empty TStringList object just before assigning meebetalers to trans[aantaltrans].meebetalers.
procedure VoegTransToe(naam, betaalpers: string; bedrag: currency;
meebetalers: TStringList; datum: TDateTime);
begin
aantaltrans:= aantaltrans+1;
trans[aantaltrans].naam:=naam;
trans[aantaltrans].pers.naam:=betaalpers;
trans[aantaltrans].bedrag:=bedrag;
trans[aantaltrans].datum:=datum;
// meebetalers:= TStringList.Create; // <-- GET RID OF THIS!
trans[aantaltrans].meebetalers:= TStringList.Create;
trans[aantaltrans].meebetalers.Assign(meebetalers);
//meebetalers.Free; // <-- AND THIS!
end;
Don't forget to Free() the input TStringList object when you are done using it:
slmeebetalers := TStringList.Create;
try
for i := 0 to Form6.CLBox.Count-1 do begin
if Form6.CLBox.Checked[i] then begin
slmeebetalers.Add(Form6.CLBox.Items[i]);
end;
end;
Unit6.VoegTransToe(..., slmeebetalers, ...);
finally
slmeebetalers.Free;
end;

Related

Saving certain data into an array from a DBGrid

I would like to ask for help.
I have been tasked with saving FighterID into an array. This data will be used to make fighter 1 ,fight, fighter 2(the data has already been sorted in descending order according to wins they have).
I could only find ways to do this with 2D arrays, i would like tom use a 1 dimensional array.
I have no idea how to save a specific columns info into the array. I have tried the following and got the following error:
[dcc32 Error] Presets.pas(53): E2010 Incompatible types: 'string' and 'procedure, untyped pointer or untyped parameter'
Code:
procedure TPresetsForm.FormActivate(Sender: TObject);
var I:integer;
var s:string;
begin
qry1.Close;
qry1.sql.add('SELECT FighterName,Wins,Sponser FROM Preset_Fighters');
qry1.Active := true;
qry1.Open;
tbl111.Sort:= 'Wins DESC' ;
for I := 1 to 6 do
begin
Fightorder[I]:=(Presets.PresetsForm.dbgrd_info.Columns[0].FieldName:=('FighterID');
end;
end;
I have no idea if this is the correct way to obtain the FighterID example (MT54).
All data is from MS Access, I hope I have provided enough information
Thanks for the help XD
Please try the following code:
var
Fightorder: array[1..6] of string;
procedure TPresetsForm.FormActivate(Sender: TObject);
var
I: Integer;
begin
qry1.Close;
qry1.Sql.Add('SELECT FighterName, Wins, Sponser FROM Preset_Fighters');
qry1.Active := True;
qry1.Open;
for I := 1 to 6 do
begin
Fightorder[I] := qry1.Fields[0].AsString;
qry1.Next;
end;
end;
I think this will help you figure it out.

How do i call a function within a function?

i'm creating a mini program in pascal to read music albums. The problem i'm facing is calling the readTracks() function within my readAlbum() function. Any help would be great, thank you :)
The current error when executing the code is:
Error: Incompatible types: got "albumRecord" expected "albumRecord.Dynamic Array Of trackRecord
type
trackRecord = record
trackName:string;
fileLocation: string;
end;
albumRecord = record
albumName:string;
tracks: array of trackRecord;
end;
function readTracks():albumRecord;
var
i:Integer;
numOfTracks:Integer;
begin
numOfTracks := readInteger('Enter number of tracks: ');
setLength(result.tracks, numOfTracks);
for i:= 0 to high(result.tracks)do
begin
Writeln('Enter Track ',i+1,' Details: ');
result.tracks[i].trackName := readString('Enter track name: ');
result.tracks[i].fileLocation := readString('Enter file
location: ');
end;
end;
function readAlbum (prompt: string): albumRecord;
begin
result.albumName := readString('Enter Album Name: ');
result.tracks := readTracks();
end;
I think you have managed to confuse yourself by the way you have declared your albumRecord.Tracks. What you should have done is to declare a trackArray type and declared your readTracks to return an instance of this array type.
Your main problem was that your readAlbum returns an albumRecord, but you had set up its tracks field to be assigned from readTracks, which returns the wrong type, i.e. albumRecord, rather than an array of tracks.
Put another way, as you have declared readAlbum to return an albumRecord, the compiler will generate code which, on entry to the function, sets up an instance of albumRecord on the stack, which is eventually returned as the return value of the function when it completes. Your code in the function is simply to fill out the fields of this record, not create another instance of it as your result.tracks := readTracks() would have done, given how you had declared readTracks.
The code below changes the declarations and code inside readTracks so that it does what you intend.
uses TerminalUserInput;
type
trackRecord = record
trackName:string;
fileLocation: string;
end;
trackArray = array of trackRecord;
albumRecord = record
albumName:string;
tracks: trackArray;
end;
function readTracks():trackArray;
var
i:Integer;
numOfTracks:Integer;
begin
numOfTracks := readInteger('Enter number of tracks: ');
setLength(result, numOfTracks);
for i:= 0 to high(result)do
begin
Writeln('Enter Track ',i+1,' Details: ');
result[i].trackName := readString('Enter track name: ');
result[i].fileLocation := readString('Enter file location: ');
end;
end;
function readAlbum (prompt: string): albumRecord;
begin
result.albumName := readString('Enter Album Name: ');
result.tracks := readTracks();
end;
begin
readAlbum('New album');
end.
Btw, I think you would find your code much clearer, when you come back to it after a while if you got into the habit of using a naming convention for declarations of record- and array types which distinguishes them from instances of them. One convention is to precede the type-name with a 'T', so your would be TtrackRecord, TalbumRecord, TtrackArray.
Also btw, in your q you say
The current error when executing the code is: Error: Incompatible types
Actually, that is not quite correct. The error occurs while the compiler is compiling the code, not when your code is executing. This is an important difference: your error is known as a compile-time error, whereas one which occurs when your program is executing (which it can only do once it has been successfully compiled) is known as a run-time error.
tracks is an array, and thus needs indexing. Which number are you reading?
In the for loop you do know how to index the array, so why can't you do it in readalbum?

Adding Values to an Array in Pascal - iIllegal Qualifier"

I am trying to create a program that prints 11 buttons so I wanted to use an array. The only change with these buttons is the name.
When I try to compile, I get the error "illegal qualifier" at my first array assignment.
type
buttonName = array[0..11] of String;
procedure PopulateButton(const buttonName);
begin
buttonName[0] := 'Sequence';
buttonName[1] := 'Repetition';
buttonName[2]:= 'Modularisation';
buttonName[3]:= 'Function';
buttonName[4]:= 'Variable';
buttonName[5]:= 'Type';
buttonName[6]:= 'Program';
buttonName[7]:= 'If and case';
buttonName[8]:= 'Procedure';
buttonName[9]:= 'Constant';
buttonName[10]:= 'Array';
buttonName[11]:= 'For, while, repeat';
end;
and in main I am trying to use this for loop
for i:=0 to High(buttonName) do
begin
DrawButton(x, y, buttonName[i]);
y:= y+70;
end;
Please know, I am very new to this and am not too confident of my knowledge in arrays, parameters/calling by constant and such.
Thank you
The parameter definition of PopulateButton() is wrong.
Try this:
type
TButtonNames = array[0..11] of String;
procedure PopulateButtons(var AButtonNames: TButtonNames);
begin
AButtonNames[0] := 'Sequence';
...
end;
...
var lButtonNames: TButtonNames;
PopulateButtons(lButtonNames);
for i := Low(lButtonNames) to High(lButtonNames) do
begin
DrawButton(x, y, lButtonNames[i]);
y:= y+70;
end;
Also pay attention to the naming conventions. Types normally begin with a T and function parameters start with an A.

pascal illegal qualifier error when calling function from a procedure

function classes(o:integer): String;
var allclasses : array[1..7] of String;
begin
allclasses[1]:= 'class1';
allclasses[2]:= 'class2';
allclasses[3]:= 'class3';
allclasses[4]:= 'class4';
allclasses[5]:= 'class5';
allclasses[6]:= 'class6';
allclasses[7]:= 'class7';
classes := allclasses[o];
end;
Above you can see a function, which should receive an integer and give a result of string that was stored in array.
procedure loadthis(chosen : string);
var f: text;
i : integer;
begin
Assign(f, 'files\'+chosen+'.txt');
Reset(f);
ReadLn(f, i);
MyChar.clas := classes[i];
end;
When this procedure is called, it calls a "classes" function. Pleae note that Mychar ir a global variable.
begin
loadthis(FileName);
ReadLn;
Readln
end.
Ant this is the main program, which calls "loadthis" procedure.
I Have no idea whats wrong, but I am getting these errors:
Wrong amount of parameters specified
Illegal qualifier
Both errors come from this line:
MyChar.clas := classes[i];. I have really no idea what is wrong, maybe I can not call a function from a procedure ? Please help.
You're trying to access it as an array index, but it needs to be a function call:
MyChar.clas := classes(i); { note () instead of [] }
You should probably add some range checking, too. What happens if someone puts 20 in the text file? Your array only has items at indexes 1 through 7, so you'll get a runtime error when you call classes(20) with the out of range value.
(You could probably use a constant array for allclasses to lessen your code as well, but your instructor probably haven't gotten that far yet.)
Given your comment about not having an instructor, here's a suggestion about a better way to handle the function:
function classes(o:integer): String;
const
allclasses: array[1..7] of string = ('class1',
'class2',
'class3',
'class4',
'class5',
'class6',
'class7');
begin
{
Low() returns the lowest index of the array, and
High() returns the highest. The if statement makes sure
that o is between them. It is the range check I mentioned.
}
if (o >= Low(allclasses)) and (o <= High(allclasses)) then
classes := allclasses[o]
else
classes := '';
end;

Problem with checking ADOTable field values

I'm having yet another problem with Delphi. I wrote a piece of code that should check if a field in a database table equals to 0, and if that is true, changes font color and caption of a certain button. It runs on creation of the main form. However, when I run the program, nothing happens - the program does not appear and I get no errors. I seriously don't know what's wrong, seems like some kind of an infinite loop.
Here's the code:
procedure TForm1.FormCreate(Sender: TObject);
begin
ADOTableStorage.First;
while not ADOTableStorage.Eof do
If ADOTableStorage.FieldByName('amount').AsInteger = 0 then
begin
btStorage.Font.Color := clRed;
btStorage.Caption := 'Some items are out of stock!';
Break;
end;
ADOTableStorage.Next;
end;
Note: The ADOTableStorage table is a on the detail table in a Master-Detail connection.
Thanks!
I guess you are missing a begin/end in the while loop. Try this.
procedure TForm1.FormCreate(Sender: TObject);
begin
ADOTableStorage.First;
while not ADOTableStorage.Eof do
begin
If ADOTableStorage.FieldByName('amount').AsInteger = 0 then
begin
btStorage.Font.Color := clRed;
btStorage.Caption := 'Some items are out of stock!';
Break;
end;
ADOTableStorage.Next;
end;
end;

Resources