convert enum to string and back lazarus / 62-General ---------------------------------------------------------------------- TBug · 2015-10-28 20:09 Hello to all, 1. How do I get the amount of posible enum-values from the type 'TComponentStyle'? 2. How can I convert an enum-value from TComponentStyle to a string, or get the enum-value from the string 'csInheritable'? crosspost -  german lazarusforum http://www.lazarusforum.de/viewtopic.php?f=10&t=9137 . ---------------------------------------------------------------------- Cyrax · 2015-10-28 20:59 1. High(TComponentStyle) - Low(TComponentStyle). 2. Convert to string : WriteStr(AStringVariable, AComponentStyleVariable)     Convert from string : ReadStr(AStringVariable, AComponentStyleVariable) ---------------------------------------------------------------------- TBug · 2015-10-28 22:07 Thank you, but the first part of your answer doesn't work. Quote from: Cyrax on October 28, 2015, 09:59:03 pm1. High(TComponentStyle) - Low(TComponentStyle). lInt := (High(TComponentStyle) - Low(TComponentStyle));  IDE-Output: Quoteudatamoduleglobalfunc.pas(778,35) Error: Operation "-" not supported for types "" and "" I need to do something like this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function HGTAnchorKindToString(AValue: TAnchorKind): String;begin  Result := GetEnumName(TypeInfo(TAnchorKind),Ord(AValue));end; function HGStringToTAnchorKind(AValue: String): TAnchorKind;begin  Result := TAnchorKind(GetEnumValue(TypeInfo(TAnchorKind),AValue));end;  Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TDM_GlobalFunc.ListTAnchorKindAssignTo(ADest: TStrings);var  lEnumValue: TAnchorKind;begin  if (FListTAnchorKind.Count = 0) then   begin    for lEnumValue := Low(TAnchorKind) to High(TAnchorKind) do   begin      FListTAnchorKind.Add(HGTAnchorKindToString(lEnumValue));     end;   end;  ADest.Assign(FListTAnchorKind);end;  Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TF_HGFormPanel.UpdateComponentValues;var  lEnumValueAnchorKind: TAnchorKind;begin    for lEnumValueAnchorKind := Low(TAnchorKind) to High(TAnchorKind) do     begin      lIndex := CLB_Anchors.Items.IndexO f(HGTAnchorKindToString(lEnumValueAnchorKind));      if (lIndex >= 0) then       begin        CLB_Anchors.Checked[lIndex] := (lEnumValueAnchorKind in MyComponent.Anchors);       end;     end; end;  This works with e.g. TControlCellAlign but not with TComponentStyle or any kind of type declared like: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i TComponentStyle = set of (csInheritable, csCheckPropAvail, csSubComponent, csTransient); ---------------------------------------------------------------------- Bart · 2015-10-28 22:10 Quote from: TBug on October 28, 2015, 11:07:03 pm Quote from: Cyrax on October 28, 2015, 09:59:03 pm1. High(TComponentStyle) - Low(TComponentStyle). lInt := (High(TComponentStyle) - Low(TComponentStyle));  IDE-Output: Quoteudatamoduleglobalfunc.pas(778,35) Error: Operation "-" not supported for types "" and "" Try (untested): Code: [Select]  lInt := Ord((High(TComponentStyle))- Ord(Low(TComponentStyle))); Bart ---------------------------------------------------------------------- taazz · 2015-10-28 22:58 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function GetSetValues(const aSet:PTypeInfo):string;var  vData1 : PTypeData;  vData2 : PTypeData;  vCntr  : Integer;begin  Result := '';  if aSet^.Kind = tkSet then begin    vData1 := GetTypeData(aSet);    vData2 := GetTypeData(vData1^.CompType);    for vCntr := vData2^.MinValue to vData2^.MaxValue do      Result := Result+ GetEnumName(vData1^.CompType,vCntr)+LineEnding;  end;end; ---------------------------------------------------------------------- TBug · 2015-10-29 12:02 Thanks a lot. The sample-code posted by taazz works fine for me. But no I have another problem. I can't find a way to pass 'csInherited' as a parameter of a function, or as "Result". Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function HGTComponentStyleValueToString(AValue: T???): String;begin  WriteStr(Result , AValue)end;  Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function HGStringToTComponentStyleValue(AString: String): T???;begin  ReadStr(AString , Result)end;  WriteStr uses a type named "Arguments" for the 2. parameter, but I couldn't find a unit where it is declared. So I cannot use this type. There are several types I tryed e.g. "TOrdinal" and "TSetElement", but don't know in which units they are declared. . ---------------------------------------------------------------------- taazz · 2015-10-29 12:32 Quote from: TBug on October 29, 2015, 01:02:00 pmThanks a lot. The sample-code posted by taazz works fine for me. But no I have another problem. I can't find a way to pass 'csInherited' as a parameter of a function, or as "Result". Use the same trick as is used on the GetEnumName function aka declare it as a integer and use a cast (or ord) to pass the value. ---------------------------------------------------------------------- TBug · 2015-10-29 12:50 Thanks for this highspeed-answer! Quote from: taazz on October 29, 2015, 01:32:11 pmUse the same trick as is used on the GetEnumName function aka declare it as a integer and use a cast (or ord) to pass the value. Thats only the 2. choice to do it, because other functions of the same style are declared with the right types and doesn't need any casts. Therefor I actually don't want to use an integer as parameter-type.  Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function HGStringToTAlign(AValue: String): TAlign;function HGStringToTAlignment(AValue: String): TAlignment;function HGStringToTAnchorKind(AValue: String): TAnchorKind;function HGStringToTBiDiMode(AValue: String): TBiDiMode;function HGStringToTBorderIcon(AValue: String): TBorderIcon;function HGStringToTBorderStyle(AValue: String): TBorderStyle;function HGStringToTCheckBoxState(AValue: String): TCheckBoxState;function HGStringToTComboBoxStyle(AValue: String): TComboBoxStyle;function HGStringToTComponentStyle(AValue: String): TComponentStyle;function HGStringToTControlCellAlign(AValue: String): TControlCellAlign;function HGStringToTControlStyleType(AValue: String): TControlStyleType;... ---------------------------------------------------------------------- taazz · 2015-10-29 13:10 Quote from: TBug on October 29, 2015, 01:50:23 pmThanks for this highspeed-answer! Quote from: taazz on October 29, 2015, 01:32:11 pmUse the same trick as is used on the GetEnumName function aka declare it as a integer and use a cast (or ord) to pass the value. Thats only the 2. choice to do it, because other functions of the same style are declared with the right types and doesn't need any casts. Therefor I actually don't want to use an integer as parameter-type.  Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function HGStringToTAlign(AValue: String): TAlign;function HGStringToTAlignment(AValue: String): TAlignment;function HGStringToTAnchorKind(AValue: String): TAnchorKind;function HGStringToTBiDiMode(AValue: String): TBiDiMode;function HGStringToTBorderIcon(AValue: String): TBorderIcon;function HGStringToTBorderStyle(AValue: String): TBorderStyle;function HGStringToTCheckBoxState(AValue: String): TCheckBoxState;function HGStringToTComboBoxStyle(AValue: String): TComboBoxStyle;function HGStringToTComponentStyle(AValue: String): TComponentStyle;function HGStringToTControlCellAlign(AValue: String): TControlCellAlign;function HGStringToTControlStyleType(AValue: String): TControlStyleType;... Tcomponentstyle is a set not an enum type it does not have a base enum type declared your only choice if you do not want to cast is to use the set type. eg Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function ComponentStyleTostring(const aStyle:TComponentStyle):string;function StringToComponentStyle(const aSTyle:String):TComponentStyle; The details are already coded for you, take a look on the SetToString and StringToSet Functions in typInfo unit. ---------------------------------------------------------------------- wp · 2015-10-29 13:30 Here's another problem related: In one of the testing routines of fpspreadsheet I am converting another set to a string. Here is the code which works with fpc 2.6.4: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TsFontStyle = (fssBold, fssItalic, fssStrikeOut, fssUnderline);  TsFontStyles = set of TsFontStyle;var  fs: TsFontStyles;  s: String;//...  s := GetEnumName(TypeInfo(TsFontStyles), integer(fs)); When I run this in fpc 3.1.1 the compiler complains in line 8 about the "integer": 'Illegal type conversion: "TsFontStyles" to "LongInt"'. I have to replace it by a cast to "byte" to make it work. Why? And is there a working solution for both versions without an IFDEF? ---------------------------------------------------------------------- garlar27 · 2015-10-29 14:22 Quote from: Bart on October 28, 2015, 11:10:47 pmTry (untested): Code: [Select]  lInt := Ord((High(TComponentStyle))- Ord(Low(TComponentStyle))); I know is untested but Please be aware of this: These class of enum types are Zero based. for: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TComponentStyle = set of (csInheritable, csCheckPropAvail, csSubComponent,    csTransient); we have the following values:    Ord(Low(TComponentStyle)) = 0    Ord(High(TComponentStyle)) = 3 High(TComponentStyle) + 1 will return the the TComponentStyle's count. EDIT: This is not due to the zero based, is a mathematic's thing: If you have let's say 7 elements and are 1 based order (from 1 to 7). Doing 7-1 to get the count won't work because you are excluding the first operator. Thus if you wish to obtain a count from a substraction you need to add 1 to the substraction and it would be something like: Code: [Select]  lInt := Ord((High(TAnyEnumeratedType))- Ord(Low(TAnyEnumeratedType))) + 1; ---------------------------------------------------------------------- Cyrax · 2015-10-29 14:59 Quote from: wp on October 29, 2015, 02:30:34 pmHere's another problem related: In one of the testing routines of fpspreadsheet I am converting another set to a string. Here is the code which works with fpc 2.6.4: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TsFontStyle = (fssBold, fssItalic, fssStrikeOut, fssUnderline);  TsFontStyles = set of TsFontStyle;var  fs: TsFontStyles;  s: String;//...  s := GetEnumName(TypeInfo(TsFontStyles), integer(fs)); When I run this in fpc 3.1.1 the compiler complains in line 8 about the "integer": 'Illegal type conversion: "TsFontStyles" to "LongInt"'. I have to replace it by a cast to "byte" to make it work. Why? And is there a working solution for both versions without an IFDEF? Hmm, which revision of FPC 3.1.1 (SVN trunk) do you use because I don't see such error? I use r32185 and it is compiled with these options : Quoteclean all install OPT=-gw2 -godwarfsets -godwarfmethodclassprefix -gl -O- -Xs- -Si- -vbq -XX -CX -dTEST_WIN32_SEH COMPILER_OPTIONS=-gw2 -godwarfsets -godwarfmethodclassprefix -gl -O- -Xs- -Si- -vbq -XX -CX -dTEST_WIN32_SEH INSTALL_PREFIX=F:\free_pascal_and_lazarus\fpc\i386\trunk\binary\fpc_tr unk UPXPROG=echo IDE=1 REVSTR=32185 ALLOW_WARNINGS=1 NOWPOCYCLE=1 EDIT : I compiled your test case with these options : -MObjFPC -Scghi -gw2 -godwarfsets -gl -l -vewnhibq -FiE:\temp\lib\i386-win32-win32-30101 -Fu. -FUE:\temp\lib\i386-win32-win32-30101\ -FEE:\temp\bin\i386-win32-win32-30101\ -godwarfmethodclassprefix ---------------------------------------------------------------------- wp · 2015-10-30 12:01 Strange. I updated fpc and Laz via fpcup (fpc r32196, Laz r50199) and don't see the error in a simple test program (attached). But I still see it when I compile the test program of fpspreadsheet (spreadtestgui in folder "tests"). On the other hand, as I see now this is not the main issue. The main issue is that GetEnumName for a set type always seems to return the same string ("CharSet") whatever elements are included in the set - see attached demo. Therefore, GetEnumName is not a good candidate to compare sets as I am doing in the fpspreadsheet test (will be fixed soon). [EDIT] Regarding the issue with casting the set to integer or byte I found out that this is not caused by the compiler version, but by the compiler mode: The demo uses mode objpas, but if I switch it to mode Delphi (that what the spreadtestgui has as well) then the cast to byte must be used. Please note a few posts below that Delphi XE2 requires the cast to byte when calling GetEnumName. Therefore, everything fine! ---------------------------------------------------------------------- Leledumbo · 2015-10-30 15:54 Quote from: wp on October 30, 2015, 01:01:02 pmOn the other hand, as I see now this is not the main issue. The main issue is that GetEnumName for a set type always seems to return the same string ("CharSet") whatever elements are included in the set - see attached demo. Therefore, GetEnumName is not a good candidate to compare sets as I am doing in the fpspreadsheet test (will be fixed soon). I'm amazed that GetEnumName works for sets. AFAIK it's only for enumerated types and if you want to print a set as string, you have to loop over it (using for-in loop) and call GetEnumName on each element instead. ---------------------------------------------------------------------- wp · 2015-10-30 16:48 I think the GetEnumName of a set either should execute the code that you propose, or it should not compile at all. A candidate for a possible bug report? I checked with Delphi XE2: The demo does compile, but only after changing the type cast of the set to "byte" (instead of "integer"). But at runtime an exception is generated at the GetEnumNume line. Based on taazz's code above I modified my demo to display correct strings for the font styles, and to do also the conversion from strings back to a set: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function GetSetName(const aSet:PTypeInfo; Value: Integer):string;var  vData1 : PTypeData;  vData2 : PTypeData;  vCntr  : Integer;  v: Integer;begin  Result := '';  if aSet^.Kind = tkSet then begin    vData1 := GetTypeData(aSet);    vData2 := GetTypeData(vData1^.CompType);    for vCntr := vData2^.MinValue to vData2^.MaxValue do      if (Value shr vCntr) and 1 <> 0 then        Result := Result+ GetEnumName(vData1^.CompType,vCntr)+',';    if Result <> '' then Delete(Result, Length(Result), 1);  end;end; function GetSetValue(const aSet:PTypeInfo; Name: String): Integer;var  vData1 : PTypeData;  vData2 : PTypeData;  vCntr  : Integer;  p      : Integer;begin  Result := 0;  if aSet^.Kind = tkSet then begin    vData1 := GetTypeData(aSet);    vData2 := GetTypeData(vData1^.CompType);    for vCntr := vData2^.MinValue to vData2^.MaxValue do begin      p := pos(GetEnumName(vData1^.CompType, vCntr), Name);      if p = 0 then        Continue;      if (p = 1) or (Name[p-1] = ',') then        Result := Result or (1 shl vCntr);    end;  end;end; { TForm1 } procedure TForm1.CbBoldClick(Sender: TObject);var  fs: TFontStyles;  s: String;begin  fs := [];  if CbBold.Checked then begin    Memo1.Lines.Add('Bold: yes');    Include(fs, fsBold);  end else    Memo1.Lines.Add('Bold: -');   if CbItalic.Checked then begin    Memo1.Lines.Add('Italic: yes');    Include(fs, fsItalic);  end else    Memo1.Lines.Add('Italic: -');   if CbUnderline.Checked then begin    Memo1.Lines.Add('Underline: yes');  Include(fs, fsUnderline);  end else    Memo1.Lines.Add('Underline: -');   if CbStrikeout.Checked then begin    Memo1.Lines.Add('Strikeout: yes');    Include(fs, fsStrikeOut);  end else    Memo1.Lines.Add('Strikeout: -');   s := GetSetName(TypeInfo(TFontStyles), integer(fs));  Memo1.Lines.Add('GetSetName:  ' + s);  Memo1.Lines.Add('GetSetValue: ' + IntToStr(GetSetValue(TypeInfo(TFontStyles), s)));  Memo1.Lines.Add(' -----------------------------------------------------');  Memo1.Lines.Add('');end;  @taazz: Since this is based on your code: Would you allow me to add this to bug tracker? ---------------------------------------------------------------------- taazz · 2015-10-31 05:42 Quote from: wp on October 30, 2015, 05:48:05 pm@taazz: Since this is based on your code: Would you allow me to add this to bug tracker? Sure go ahead. I'll be honored to have any piece of code in fpc or lazarus. BUT and its a big but, I have already mentioned it in this thread, why don't you use the functions provided in the unit typinfo named SetToString and StringToSet which does exactly what the name implies? I see nothing here that is not allready covered on those functions. ---------------------------------------------------------------------- wp · 2015-10-31 10:16 Quote from: taazz on October 31, 2015, 06:42:15 amI have already mentioned it in this thread, why don't you use the functions provided in the unit typinfo named SetToString and StringToSet which does exactly what the name implies? I see nothing here that is not allready covered on those functions. Oh, I missed this one. Thanks for pointing this out to me.