lua-users home
lua-l archive

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


2012/5/30 Tim Hill <drtimhill@gmail.com>:

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

> function usertype(v)
> local ty = getmetatable(v).__type
> return ty and "_" .. ty or type(v)
> end
>
> Of course, it's not necessary to add this to the language; after all I just
> wrote the code in the above example. However, I feel that this is a generic
> feature that needs to always be available for people who are writing addon
> libraries or packages for Lua.
>
> Thoughts anyone?

Actually your sentence starting "Of course" describes my thoughts
pretty much exactly.  I'm much too set in my habits to start writing
"usertype" now.  But you can have you cake and eat it, thus:

origtype = type
function type(obj)
  local m=getmetatable(obj)
  local t=origtype(obj)
  if not m or not m.type then return t end
  return m.type(obj)
end

print(type"abcdefghijklmnopqrstuvxyz") --> string
print(type(io.stderr)) --> userdata

getmetatable"".type = function(s) return 'string'..#s end
getmetatable(io.stdin).type = io.type

print(type"abcdefghijklmnopqrstuvxyz") --> string25
print(type(io.stderr)) --> file