lua-users home
lua-l archive

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


Yes, I forgot the __index, my bad. The point remains that once this is fixed,

o:__tostring()

and

getmetatable(o).__tostring(o)

are not equivalent, since a protected metatable might prevent the latter to work, precisely because getmetatable checks the __metatable field, whereas the rest of the language doesn't. But this isn't what the thread is about anyway :-).


-----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 13:23
À : Lua list
Objet : Re: Enhanced tostring

> 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"

getmetatable(o) returns false and so the message is expected.

> print( o:__tostring()) -- causes "attempt to call method '__tostring' (a nil value)"

o does not have a __tostring method and so the message is expected.
Try adding this
	meta.__index = meta

The __tostring method is used by "tostring" and so print(o) works
even if the metatable is proteced.