lua-users home
lua-l archive

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


Hello,

I would like to be able to pass a table to string.format().

For example:

local aTable = { "a", "b", "c" }

setmetatable( aTable, { __tostring = function( aTable ) return table.concat( aTable, ", " ) end } )

print( aTable )

> a, b, c

print( ( "%s" ):format( aTable ) )

Unfortunately, this doesn't work:

lua: TestNaming.lua:89: bad argument #1 to 'format' (string expected, got table)
stack traceback:
        [C]: in function 'format'

Instead, one needs to explicitly convert the table to a string before hand:

print( ( "%s" ):format( tostring( aTable ) ) )

> a, b, c

Any reason(s) why string.format() do not consider the table metamethods before doing its things?

Perhaps something along these lines:

local _format = string.format

string.format = function( aString, ... )
        local someArguments = { ... }
        local aLength = select( "#", ... )

        for anIndex = 1, aLength do
                local aValue = someArguments[ anIndex ]

                if type( aValue ) == "table"
                        and getmetatable( aValue ) ~= nil
and type( getmetatable( aValue )[ "__tostring" ] ) == "function" then

                        someArguments[ anIndex ] = tostring( aValue )
                end
        end

        return _format( aString, unpack( someArguments, 1, aLength ) )
end

print( ( "%s" ):format( aTable ) )

> a, b, c

The same applies to error(), table.concat() and other Lua functions. They all seem to ignore __tostring and just throw an exception when confronted with anything beside a regular string. Any reasons for ignoring the table metamethods?

Thoughts?

Cheers

--
PA, Onnay Equitursay
http://alt.textdrive.com/