lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Mike Pall wrote:
> local t = setmetatable({}, { __index = function() return 0 end })
> for c in string.gmatch(io.read("*a"), ".") do t[c] = t[c] + 1 end
> table.foreach(t, print)

I like it! You could replace the middle line with:

io.read("*a"):gsub("(.)", function(c) t[c] = t[c] + 1 end)

Gotta love those string functions.

I tried to clean up the special character output with a new last line:

table.foreach(t, function (c, n) print(("%q %4d"):format(c, n)) end)

I was surprised to find that "%q" did not escape the newline (linefeed)
character with "\n" but with "\
". The reference manual describes this as the proper behavior, even
including an embedded newline in its example. I've read the manual front
to back a number of times, yet I was still surprised by this.

It seems like using "\n" would give an exact representation of the
string even if it is written to a file that is shared between machines
with different line termination characteristics. My experience with this
sort of thing is that there was a reason for it, but the only reason I
can come up with (allowing multi-line quoted strings) is easily
dismissed by using '[['.

Is it done this way explicitly so it can automatically pick up the
LF/CR+LF of the host system when the string is re-read?

It would be an interesting project (not volunteering - yet!) to create
an Annotated Lua Reference Manual that includes rationales for various
design decisions. Both the reference manual and PIL have a few examples
of such annotations. Ada had such an annotated reference manual and it
was invaluable when I was learning it. It made me think from the
compiler's point of view, which is always helpful.

As always, it's about the time...

Doug

-- 
Innovative Concepts, Inc. www.innocon.com 703-893-2007 x220