lua-users home
lua-l archive

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


On Tue, 19 Mar 2002, nikdo79 wrote:

> Hi there,
> 
> there's no entry in the Metatable for tostring/tonumber?
> I can't make a Object-Table to say it's class when being tostring'ed?
> so that e.g.:

You can add this fairly easily: (untested code)

    _tostring = tostring
    function tostring(obj)
        local tsf = _tostring
        local mt = metatable(obj)
        if mt~=nil then
            tsf = mt.tostring or tsf
        end
        return tsf(obj)
    end

The version for tonumber is similar: (again, untested)

    _tonumber = tonumber
    function tonumber(obj)
        local tnf = _tonumber
        local mt = metatable(obj)
        if mt ~= nil then
            tnf = mt.tonumber or tnf
        end
        return tnf(obj)
    end
        
Of course you can also implement these in 'C' if you need to.

  - Tom

> myobject=Car.New{TopSpeed=160,Brand='Opel',Type='Corsa'}
> 
> write(tostring(myobject))
> 
> would result in:
> Car Object: Opel Corsa, 160 km/h max
> 
> That's right, isn't it?
> 
> Dom
> 
>