lua-users home
lua-l archive

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


On 06/11/2012 10:46, Luiz Henrique de Figueiredo wrote:
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?

string.format in Lua 5.2 already does that, doesn't it?

function test(x) print(x,string.format("%s",x)) end

test(1)
test(nil)
test("hello")
test(true)
test(print)
test(io.stdin)

Great, but a mystery. Also checked:

f({1,2,3})
t = {}
setmetatable(t, {__tostring = function(t) return "*t*" end})
f(t)

(wanted to be sure __string is taken into account)

A point I don't understand is that yesterday when using format with %s on table args (some with custom __tostring) I received as usual the error about "got table, expected string" (or similar). So, what did I do wrong?

Another point I did not realised is the famous number<->string auto-conversion applies here [*]. In my original post, I complained using %s and converting every argto strings before passing them to format would prevent correctly formatting numbers with %d or %f. Actually, no! Lua converts back to number when it expects one due to the % code used. So that using this original trial of printf (without filtering only %s format before string conversion, I get in tests output like:

The following is the format string used:
   %d | %d | %05d | %05d | %9.5f | %9.5f | %s | %s

The following are the args passed to printf:
   1, 123, 123, -123, 1.123, -1.123, 'one', L{1,2,3}

Result:
   1 | 123 | 00123 | -0123 |   1.12300 |  -1.12300 | one | L{1, 2, 3}

(l is a custom type (alias of List) for array-like tables)

Denis

[*] I also always forget the other way round, tostring-ing numbers as in
   print("duration: " .. tostring(n) .. " turns")