Wren Lee wrote:
DEC-Pascal has the ability to initialise a boolean or an enumerated type from a text file.The text is case insensitive and is read just as any other variable. Is there a way to do this with GPC?
No. For Booleans, it would not be too difficult to implement, but for enum types, it would require that they're values (which are program identifiers otherwise) be kept in the executable which is not provided for currently (besides debug info).
If not, are there any good ways to emulate this behaviour?
Something like the following. It also illustrates the limitations...
program ReadBooleanEnumDemo;
uses GPC;
procedure ReadWord (var f : Text; var s : String); const WordChars = ['A' .. 'Z', 'a' .. 'z', '_', '0' .. '9']; begin s := ''; while f^ in SpaceCharacters do if EOLn (f) then Readln (f) else Get (f); while not EOF (f) and not EOLn (f) and (f^ in WordChars) do begin s := s + f^; Get (f) end end;
function ReadBoolean (var f : Text) : Boolean; var s : TString; begin ReadWord (f, s); LoCaseString (s); if s = 'false' then ReadBoolean := False else if s = 'true' then ReadBoolean := True else begin IOErrorCString (464, FileName (f)); { error when reading from % } ReadBoolean := False end end;
function ReadEnum (var f : Text; const IDs : array of PString) : Integer; var s : TString; i : Integer; begin ReadWord (f, s); LoCaseString (s); i := Low (IDs); while (i <= High (IDs)) and (LoCaseStr (IDs [i]^) <> s) do Inc (i); if i <= High (IDs) then ReadEnum := i else begin IOErrorCString (464, FileName (f)); { error when reading from % } ReadEnum := 0 end end;
procedure WriteEnum (var f : Text; EnumVal : Integer; const IDs : array [m .. n : Integer] of PString); begin Write (f, IDs [EnumVal]^) end;
type TFruit = (Apple, Orange, Banana);
const FruitIDs : array [TFruit] of PString = (@'Apple', @'Orange', @'Banana');
var BoolVar : Boolean; FruitVar : TFruit;
begin Write ('Enter a boolean and a fruit: '); BoolVar := ReadBoolean (Input); FruitVar := TFruit (ReadEnum (Input, FruitIDs)); { we have to cast the result to the enum type } Writeln ('You entered:'); Writeln (BoolVar); WriteEnum (Output, Ord (FruitVar), FruitIDs) end.
Frank