[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: __tostring and string.format
- From: steve donovan <steve.j.donovan@...>
- Date: Mon, 6 Dec 2010 08:11:55 +0200
On Mon, Dec 6, 2010 at 6:45 AM, HyperHacker <hyperhacker@gmail.com> wrote:
> Why does string.format not call tostring() on arguments given as %s?
> (and for that matter tonumber() for %d/%u, which in turn could call a
> __tonumber metamethod...)
This bit me recently and I'm now using a more paranoid version:
local format = string.format
function formatx (fmt,...)
local args = {...}
local i = 1
for p in fmt:gmatch('%%s') do
if type(args[i]) ~= 'string' then
args[i] = tostring(args[i])
end
i = i + 1
end
return format(fmt,unpack(args))
end
print(formatx('%s=%s',10,nil))
string.format is one of the important string functions and it would be
good if this kind of behaviour was built-in and hence more efficient.
But then we could ask the very same question about table.concat, which
also doesn't use tostring...
steve d.