lua-users home
lua-l archive

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


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