[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: Perl-like strings...?
- From: "Paul Hudson" <phudson@...>
- Date: Mon, 9 Oct 2006 10:53:27 +0100
Or even
"Name $fname, Rank: $rankstr, Serial: $sernum" % {fname="Andy",
rankstr="Captain", sernum=1234}
which is closer to the original syntax suggestion. I've used this, with a
function rather than an operator
-- replace $<whatever> foo in 's' with the value of the corresponding entry
in 'l'.
-- (leaving it alone if there is no such key in l so that more than one call
to expand
-- can be used to expand all the variables)
function expand (s, l)
return (string.gsub(s, "$([%w_]+)",
function (n)
return l[n] or ("$" .. n)
end))
end
(This is 5.0, it's slightly simpler in 5.1 because gmatch doesn't substitute
if it gets a nil for the value to substitute)
So the above example is
expand("Name $fname, Rank: $rankstr, Serial: $sernum", {fname="Andy",
rankstr="Captain", sernum=1234})
P.
-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br] On Behalf Of Andy Stark
Instead of this, I would recommend using one of the operators currently
undefined for strings (it could be the % operator, say) and use it to
interpolate values from a table. This is done by detecting placeholders in
the string. For example:-
"Name: [1], Rank: [2], Serial: [3]" % {"Andy", "Captain", 1234}
Of course it doesn't have to use square brackets. One possibility is to
use % within the string like printf does - familiar and consistent with
the choice of operator.
I think this is better because it doesn't require anything major to be
added to the language and is also good from a maintenance point of view.
If you want to change the ordering of the name, rank and serial number,
you just change the ordering of the placeholders; you don't need to alter
any of the code. This is good for internationalisation if nothing else.
A further refinement would be to allow non-numeric indices in the template
and the table, so you could write:-
"Name [fname], Rank: [rankstr], Serial: [sernum]" % {fname="Andy",
rankstr="Captain", sernum=1234}
This would be more self-documenting when the format string and the
interpolation code are kept in separate files, but it obviously adds
complexity to the implementation.
&.