stevedonovan/Penlight — pull request #110 by andrewstarks (2014-03-04 17:13:00+00:00)
Title: More Robust Quoted Strings

Hey Steve,

I wanted to share this work with you, in case you found it useful. Please ignore/reject it if you don't find that it fits with Penlight's goals.

This pull request includes `stringx.quote_string` and changes to `pretty.write`. `quote_string` wraps a string such that reloading that string from a chunk of Lua code produces identical results:
```lua
mystr = "\n[[\n My tricky ]======] string.\n]]"
mystr2 = load("return " .. stringx.quote_string(mystr))()
assert(mystr == mystr2)
```
It provides the same facilities as `("%q"):format(str)`, plus:

* Uses long quotes when it finds a pattern that matches the long-quote pattern (begin or end, balance doesn't matter) or when it finds a `\n`.
* Adds an extra `\n` at the beginning, if found.
* When Long quotes are used, it always uses a number of `=` signs that is one greater than any long-quotes that are embedded into the string.

The second, and highly related, changes were to pretty.write:

* Uses `stringx.quote_string` instead of internal, literal methods.
* Adds a space in front and in back of string, when long strings are used for key values:

```lua
my_table = {
[ [[
My crazy key
]] ] = "foo"
}
```

* Because of the first change, now embedded long-strings can round-trip through the pretty printer. Nested long-strings would not compile in Lua.

Finally, a small patch was added for pretty.number:

* Added check for Lua 5.3. Locally patched `tostring` so that it returns `123` instead of `123.0`. Without this patch, pretty.number was broken.

I also added tests and local function documentation, although this should be re-read and verified before accepting.