lua-users home
lua-l archive

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


Hello,

Is there a kind of Lua equivalent of Go's %v formatting tag (or python's %s for non-strings), applying tostring on the arg?

Or, is there a way to write a kind of printf (not C's) where the caller would not have to manually tostring every arg which is not a string or a number (provided a tostring func exists for the args in question), before letting it processed by format?

If we do something like:

printf  = function (fmt, ...)
   local strings = {}
   for _,elt in arg do
      strings[#strings+1] = tostring(elt)
   end
   print(format(fmt, unpack(strings)))
end

then the caller must specify %s for every arg, loses the opportunity to format numbers and tostring is uselessly invoked on strings (at least in code). Are there existing solutions for this?

Denis

PS:
I have in mind something like this:

               (Lua internal)
               representation
                     |
            ---->--------->----
            |                 |
 (parser) in|put           out|put %n tostring
            |                 |
            ----<---------<----
                     |
                  notation
                (programmer)

A bidirectional correspondance between user notation and Lua data elements.
I call that 'notation' (and %n, which I guess is unused) mainly because 'representation' and 'expression' have other meaning in programming, and 'note' as a dedicated function would be great (maybe 'writing' and %w would be good as well, but 'write' is already used). This is mainly for programmer feedback in debug, testing, maintenance... but indeed can be used else where.

I'm aware of the issues of table output (including serialisation) and am not advocating here for a universal tostring; this is a distinct issue. I just wish a tag for invocation of tostring, _provided_ tostring is defined. It's up to the programmer to do the job. In the present state of things, as far as I know, even when the job is done and there is a tostring for a given kind of data, it is not called; i mean, it not called by format, unlike when print alone is used. (I'm really fed up of calling tostring on about everything I need feedback about... feels like prehistoric programming compared to the agility and flexibility Lua provides.)