lua-users home
lua-l archive

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


On Thu, Oct 22, 2009 at 4:03 PM, Geoff Leyland wrote:
> Rima has an "enhanced" tostring that I've called repr (I pinched the name
> 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].  I once posted, though have since removed, an idea like
that on the wiki [3].

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?  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).  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 [6], but many of those
languages differentiate field and method namespaces.  Is this the
reason that metamethods exist in Lua?

If we were to introduce a serialization API (e.g. repr), would we make
the operation a method or metamethod?

[1] http://docs.python.org/library/functions.html#repr
[2] http://docs.python.org/library/functions.html#str
[3] http://web.archive.org/web/20080101100134/lua-users.org/wiki/GeneralizedTostring
[4] http://www.lua.org/wshop06/Silverstone.pdf
[5] http://lua-users.org/lists/lua-l/2009-06/msg00394.html
[6] http://docs.python.org/reference/datamodel.html#special-method-names