lua-users home
lua-l archive

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


	Hi Tim

On Wed, 30 May 2012, Tim Hill wrote:
However, it seems to me that there is one hole in this clean
model: the inability of a metatable to project a "type" into the
Lua code space. Specifically, regardless of metatable, the value
of type(someuserdata) is always "userdata".
	This is consistent with type(sometable).  The inability also
affects tables with metatables.

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?
	I would suggest to return a second value:

-- Untested!
function usertype(v)
	local tv = type(v)
	if tv == "table" or tv == "userdata" then
		local mt = getmetatable(v)
		return tv, mt and mt.__type or mt
	else
		return tv
	end
end

	It can be used in place of type(), but it has extra cost...
	In fact, I discarded type-checking in my Lua code (I experimented
a library to check types and a tool to remove it from production code,
but gave up: the time spent on it were bigger than the bugs it warned),
which is one use of this kind of function.  In other situations, when I
need to check the type to avoid problems, a generic test like that is an
overkill (for me, at least) then I use a direct solution (like checking
an especific field of the value or something like that).

	Regards,
		Tomás