How to know if a value is a luasocket object?

309 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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

6
On

You don't. Generally, you're expected to keep track of that sort of thing yourself. You trust that objects you are passed are what you expect them to be. And if you're not sure, you can always use pcall to call functions on them and catch any errors.