lua-users home
lua-l archive

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


On 06/11/2012 08:39, steve donovan wrote:
On Tue, Nov 6, 2012 at 9:07 AM, spir <denis.spir@gmail.com> wrote:
format numbers and tostring is uselessly invoked on strings (at least in
code). Are there existing solutions for this?

Here's something that works but is rather inefficient:

function printf (fmt,...)
     local args,n = {...},select('#',...)
     local idx = 1
     fmt:gsub('%%(.)',function(c)
         if c == 's' then
             args[idx] = tostring(args[idx])
         end
         idx = idx + 1
     end)
     print(fmt:format(unpack(args)))
end

printf('%s %d %f %s',{1,2},2,4.2,io.stdout)

But, this kind of stuff is much more efficient in C, since we can
quickly check for %'s in the string and modify the stack before
calling string.format.

steve d.

Thnak you very much, Steve!
About efficiency, even if generally I don't like wasting resources at all if an alternative is viable, I don't mind here, since as said it is mostly for programmer feedback, so there won't be tons of data to output (except for rare cases where a specific is generally needed anyway). (Also, I guess somehow tostring is actually not invoked if the arg is already a string?)

Denis