#1 2020-01-10 15:07:29

macfly
Member
From: Brasil
Registered: 2016-08-20
Posts: 374

[Solved] Set initial values of a record

Hello friends,

Is there any "magic" method that sets the initial values of a record?

Example:

TMyRecord = record
  MyInt : Integer;
  MyDate : TDateTime;
end;

A method that set  MyInt and MyDate to 0.

=========

Another subject (however related as a solution to this is to use classes)

@ab, could you consider moving ObjectLoadJSON to the SynCommons.pas unit?

This method is in Mormot.pas, but due to its generalization I believe it could be in SynCommons to avoid dependence on Mormot.pas.

Especially because ObjectToJSON is in SynCommons

Last edited by macfly (2020-01-10 19:45:28)

Offline

#2 2020-01-10 16:02:38

trx
Member
Registered: 2015-08-30
Posts: 30

Re: [Solved] Set initial values of a record

If your compiler supports it, you can do:

myVar := Default(TMyRecord)

Offline

#3 2020-01-10 16:32:17

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,207
Website

Re: [Solved] Set initial values of a record

ObjectToJSON() needs class RTTI and TSQLRecord, which are not available in SynCommons, but are defined in mORMot.pas.

Offline

#4 2020-01-10 16:33:21

macfly
Member
From: Brasil
Registered: 2016-08-20
Posts: 374

Re: [Solved] Set initial values of a record

Thanks for reply.

This works, but not in Delphi 7.

Se this case:

TMyRecord = record
  Name : String;
  ... 
  Date : TDatetime;
end;

var
 MR : TMyRecord;
 MR.Name := 'Jhon';
 RecordSaveJSON(MR, TypeInfo(TMyRecord ));  //<<

This raise a invalid floating point operation because Date whas not setted.

Then I need to create a function or constant to init the record.

A generic (cross-compiler) method would be of great help.

Offline

#5 2020-01-10 17:27:32

macfly
Member
From: Brasil
Registered: 2016-08-20
Posts: 374

Re: [Solved] Set initial values of a record

ab wrote:

ObjectToJSON() needs class RTTI and TSQLRecord, which are not available in SynCommons, but are defined in mORMot.pas.

Thanks ab,
I see now that if i remove mORMot.pas, ObjectToJSON returns null.

Offline

#6 2020-01-10 17:28:39

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,207
Website

Re: [Solved] Set initial values of a record

Please check RecordZero() from https://synopse.info/fossil/info/3fb0a0171a

Offline

#7 2020-01-10 17:52:38

macfly
Member
From: Brasil
Registered: 2016-08-20
Posts: 374

Re: [Solved] Set initial values of a record

Wow, you are fast!

Checking now.

Thanks ab.

PS: Maybe this new method must be in documentation as a recommendation to avoid erros in serilization.
A record with much/nested fields, are easy to bypass the initialization.


Edit: Tested RecordZero() implementation, and Working.

Last edited by macfly (2020-01-10 19:45:02)

Offline

Board footer

Powered by FluxBB