lua-users home
lua-l archive

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


It was thus said that the Great bil til once stated:
> Hi,
> is there some preferred / recommended way, to ask for the type of a
> userdata inside some Lua program?
>
> I would like a e. g. like a Lua function "testudata( udata, type)"
> corresponding to luaL_testudata, so that I could write something like
> this in Lua:
> 
>       if not testudata( variable, 'FILE*') then print ('not a file...') end

  Yes, something like:

	function testudata(value,utype)
	  local mt = getmetatable(value) -- or debug.getmetatable() 
	  return mt and mt == debug.getregistry()[utype] or false	  
	end

should work, but in some cases, this might not be a great idea.  For
instance, I have a module that presents the same API as files [1], but
returns a table, not a userdata, so that it could be passed into code that
expects file:close(), file:flush(), file:lines(), file:read(), file:seek(),
file:setvbuf and file:write() on data that isn't a file.  A check like yours
will cause that to fail.

  -spc

[1]	https://github.com/spc476/lua-conmanorg/blob/master/lua/net/ios.lua