lua-users home
lua-l archive

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


Well some really interesting discussions :) ... I tend to agree with Leo's approach which extends type() without breaking it by adding a 2nd return value derived from __type or whatever from the metatable.

For those saying "well, all you have to do is implement XXX" yes you are correct about how it can be done (there are dozens of ways). My point really was that the ability to project "metatype" information for userdata and tables is, imho, something that should be part of the standard base language. Such a facility is part of the basic contract between suppliers and consumers of objects, and so transcends individual local designs. Just like tostring() can be extended via the __tostring metafunction, so the type() function can be extended. This way, no new design pattern need be introduced, and Lua stays implementation neutral ... what is standardized is the contract BETWEEN the consumer and the supplier of type data.

As for extending type() versus some form of predicate, my feeling is that a predicate model belongs above the core layer; just like Lua does not have one baked-in object syntax, but instead provides the building blocks for many different OO paradigms, so the type() mechanism should be above any one paradigm. After all, any predicate system can really be built on top of an extended (two return value) type() function plus a conventionalized use of the second return value (string parsing etc etc).

--Tim


On May 31, 2012, at 5:37 PM, Leo Razoumov wrote:

On Wed, May 30, 2012 at 3:37 PM, Tim Hill <drtimhill@gmail.com> wrote:
To my mind, the most correct way for this to work would be for the type()
function to return the user-defined type by returning the value of
__metatable (like getmetatable()). However, this would of course break
existing code, so i feel we need a new function, usertype() that behave like
type() except when there is a __metatable field in the metatable, in which
case it returns this instead. For example:

function usertype(v)
local mt = getmetatable(v)
if mt ~= "table" return mt else return type(v)
end


In my own version of type() function I return up to two values. The
first returned value comes from original_type() function. For userdata
the second returned value is the typeinfo taken from its metatable (if
found). Usage is something like this:

local xtype, xtypeinfo= type(x)
if x == "userdata" then do_something_with_typeinfo(xtypeinfo) end

Please note, that this new type() function is backwards compatible
with the original type() in most cases. Second returned value can be
simply discarded.

--Leo--