Search code examples
lualuasocket

How to know if a value is a luasocket object?


I've noticed that luasocket doesn't seem to provide a way to know if a value is a luasocket object or not.

The usual approach of comparing metatables doesn't work, as different socket object types have different metatables. There don't seem to be any consistent values in the metatable to check either (eg, same __tosting metamethods)

So: how can one know if a value they have is a luasocket object?


Solution

  • Since you only want to know if it's a LuaSocket object so you can get the fd, why not just look to see if the object has a getfd() method? As a bonus this will work with current and future libraries that provide this method on objects, not just LuaSocket.

    This technique is known as 'duck typing'.