lua-users home
lua-l archive

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


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.