-
Notifications
You must be signed in to change notification settings - Fork 3
NEP14 Stringification
Greg Hewgill edited this page Aug 12, 2020
·
5 revisions
This proposal suggests a uniform scheme for converting data values to strings.
- The
print()
function, with a string, should print that string verbatim. - The
print()
function should accept any value of any type and print a readable (though perhaps in some cases not useful) representation. - String interpolation should follow the same rules as for the
print()
function. - The
.toString()
method should return a readable string representation of the value, and for value of typeString
it should return just the value.
> LET s: String := "hello"
> print(s)
hello
> print(s.toString())
"hello"
> print("\(s)")
hello
Here, the \(s)
string interpolation calls .toString()
on the value, except for type String
, where it doesn't.
The .toString()
method, for each type, will return:
Type | Result | Example |
---|---|---|
Boolean | Literal boolean value | FALSE |
Number | String representation of number | 1.234 |
String | The same string | hello |
Bytes | Hex notation | HEXBYTES "01 02 03" |
ENUM |
Enum item name | red |
Array | Literal array with quoted strings | ["foo", "bar"] |
Dictionary | Literal dictionary with quoted keys and string values | {"name": "foo", "value": 5} |
RECORD |
Literal record form | Item(name WITH "foo", value WITH 5) |
POINTER |
Pointer with literal class form | 0x12345678->Item(name WITH "foo", value WITH 5) |
Object |
Result of .toString() call on object |
dependent on object |
String interpolation will always call .toString()
on the interpolated value.
A new function string.quote()
will quote a given string in a form that would be acceptable in source code:
VAR s: String := "hello"
> print(s)
hello
> print(string.quote(s))
"hello"
> s := s + string.fromCodePoint(34) + "world"
> print(s)
hello"world
> print(string.quote(s))
"hello\"world"