ToStr: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: ToStr
| Old | New | Line | |
|---|---|---|---|
| 1 | + | # About | |
| 2 | + | ||
| 3 | + | **ToStr** is helper function to convert any value to a string representation, including records and arrays, in the same spirit of 'print' functions found in scripting languages. Its usefull for logging and debugging. | |
| 4 | + | ||
| 5 | + | ``` pascal | |
| 6 | + | function ToStr(const AValue; ATypeInfo: PTypeInfo): AnsiString; | |
| 7 | + | ``` | |
| 8 | + | ||
| 9 | + | Parametes: | |
| 10 | + | ||
| 11 | + | - AValue: The variable to convert to string. | |
| 12 | + | - ATypeInfo: The type information returned by 'TypeInfo' compiler intrinsic. | |
| 13 | + | ||
| 14 | + | # Download | |
| 15 | + | ||
| 16 | + | You can get the code at <https://github.com/correaelias/TypeUtils> | |
| 17 | + | ||
| 18 | + | # Examples | |
| 19 | + | ||
| 20 | + | Simple example. | |
| 21 | + | ||
| 22 | + | ``` pascal | |
| 23 | + | program test; | |
| 24 | + | uses TypeUtils; | |
| 25 | + | var | |
| 26 | + | Arr: array[1 .. 3] of Integer = (1, 2, 3); | |
| 27 | + | begin | |
| 28 | + | WriteLn(ToStr(Arr, TypeInfo(Arr))); | |
| 29 | + | end. | |
| 30 | + | ``` | |
| 31 | + | ||
| 32 | + | Example converts array of record. | |
| 33 | + | ||
| 34 | + | ``` pascal | |
| 35 | + | program Test; | |
| 36 | + | ||
| 37 | + | uses TypeUtils, SysUtils; | |
| 38 | + | ||
| 39 | + | type | |
| 40 | + | TEmployee = record | |
| 41 | + | FName: ShortString; | |
| 42 | + | FId: LongInt; | |
| 43 | + | FSalary: Currency; | |
| 44 | + | end; | |
| 45 | + | ||
| 46 | + | var | |
| 47 | + | Employees: array of TEmployee; | |
| 48 | + | I: LongInt; | |
| 49 | + | begin | |
| 50 | + | SetLength(Employees, 10); | |
| 51 | + | ||
| 52 | + | for I := 0 to High(Employees) do | |
| 53 | + | begin | |
| 54 | + | with Employees[I] do | |
| 55 | + | begin | |
| 56 | + | FName := 'John Doe ' + I.ToString; | |
| 57 | + | FId := I; | |
| 58 | + | FSalary := 2000.25 * I; | |
| 59 | + | end; | |
| 60 | + | end; | |
| 61 | + | ||
| 62 | + | WriteLn(ToStr(Employees, TypeInfo(Employees))); | |
| 63 | + | end. | |
| 64 | + | ``` | |
| 65 | + | ||
| 66 | + | It shows: | |
| 67 | + | ||
| 68 | + | `[('John Doe 0', 0, 0), ('John Doe 1', 1, 2000.25), ('John Doe 2', 2, 4000.5), `\ | |
| 69 | + | `('John Doe 3', 3, 6000.75), ('John Doe 4', 4, 8001), ('John Doe 5', 5, 10001.25), `\ | |
| 70 | + | `('John Doe 6', 6, 12001.5), ('John Doe 7', 7, 14001.75), ('John Doe 8', 8, 16002), `\ | |
| 71 | + | `('John Doe 9', 9, 18002.25)]` | |
| 72 | + | ||
| 73 | + | --- | |
| 74 | + | *From the Free Pascal wiki, page "ToStr", as it stood on 2022-08-26 after a change by Alextp, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* |
