lua-users home
lua-l archive

Re: metatable - tostring,tonumber

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


Here's a correction to my own mail:
I forgot that only tables and userdata can have metatables, so the code I
gave fails for numbers, strings, and such. To fix it the type of the
object must be checked using the type() function. So tostring might be:
 _tostring = tostring
 function tostring(obj)
 local tsf = _tostring
 if type(mt)=="table" or type(mt)=="userdata" then
 local mt = metatable(obj)
 if mt~=nil then
 tsf = mt.tostring or tsf
 end
 end
 return tsf(obj)
 end
Perhaps it would make sense to modify the metatable function so it returns
nil for objects that are not userdatas or tables?
 - Tom
On 2002年3月19日, Tom Wrensch wrote:
> On 2002年3月19日, 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
> > 
> > 
> 
> 

AltStyle によって変換されたページ (->オリジナル) /