[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Enhanced tostring
- From: Geoff Leyland <geoff_leyland@...>
- Date: Fri, 23 Oct 2009 14:29:29 +1300
On 23/10/2009, at 2:07 PM, David Manura wrote:
On Thu, Oct 22, 2009 at 4:03 PM, Geoff Leyland wrote:
Rima has an "enhanced" tostring that I've called repr (I pinched
from python, but I don't really know much about python's repr).
It's the same as tostring (so there's a corresponding __repr)
except that it
takes a second format argument.
That is [1,2].
Python's repr doesn't seem to have a format object?
I once posted, though have since removed, an idea like
that on the wiki .
Why did you remove it? I think the hard part of such an undertaking
would be to get some agreement on what the format object might contain.
Could someone remind me why Lua stringifies an object o by way of
getmetatable(o).__tostring(o) rather than o:__tostring()? Is it
because the latter is syntactic sugar for indexing operations
o.__tostring(o) and o["__tostring"](o) so this would lead to
ambiguities if o represents a hashtable with an indexing operator that
queries by key?
Certainly for me.
Rima uses proxy objects that save indexing operations for later, so
they have no fields of their own (they want to catch ALL __index and
__newindex events), they do have a metatable (with the appropriate
__index and __newindex) and the metatable has a __tostring and __repr.
These objects can certainly be 'tostring'ed, but o:__tostring() and
o.__tostring(o) won't work, they'll just get remembered.
The __methindex proposal [4,5], would probably
resolve that since it allows differentiating an object's method
namespace from its field namespace so that o:__tostring() can be
assigned different behavior from o.__tostring(o).
As it stands, this would work, but I wouldn't rule out Rima wanting to
record method calls in the future.
The lack of this
difference, I suspect, is in part why Lua introduces it's own
additional namespace (metamethods), thereby replacing o.__tostring(o)
with a similarly fashioned getmetatable(o).__tostring(o), just without
the same ":"-like syntactic sugar for doing that, but rather with
operators and wrapper functions like tostring. The metamethod concept
is absent in many other languages, e.g. Python , but many of those
languages differentiate field and method namespaces. Is this the
reason that metamethods exist in Lua?
It's certainly one reason why Lua's different, but I'm not sure that
there's a good argument for which is better. Personally, I like
metamethods and the simplicity of how Lua handles 'objects', but
that's just me.
If we were to introduce a serialization API (e.g. repr), would we make
the operation a method or metamethod?
I vote metamethod. I'd note that Rima's repr might have the wrong
name - it's not about serialisation (though I s'pose it could be)