lua-users home
lua-l archive

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


What if the object wants to protect the metatable from public access, like this?

meta =
{
  __metatable = false,
  __tostring = function(o) return "hello " .. o.name end
}

o = {}
setmetatable(o, meta)
o.name = "bob"
print( o) -- yields "hello bob"
o.name = "mick"
print( getmetatable(o).__tostring(o)) -- causes "attempt to index a boolean value"
o.name = "ted"
print( o:__tostring()) -- causes "attempt to call method '__tostring' (a nil value)"


-----Message d'origine-----
De : lua-bounces@bazar2.conectiva.com.br [mailto:lua-bounces@bazar2.conectiva.com.br] De la part de Luiz Henrique de Figueiredo
Envoyé : vendredi 23 octobre 2009 03:19
À : Lua list
Objet : Re: Enhanced tostring

> Could someone remind me why Lua stringifies an object o by way of
> getmetatable(o).__tostring(o) rather than o:__tostring()?

In my libraries and probably many others, the two expressions are equivalent.