3

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?

greatwolf
  • 20,287
  • 13
  • 71
  • 105
daurnimator
  • 4,091
  • 18
  • 34

2 Answers2

1

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

MattJ
  • 7,924
  • 1
  • 28
  • 33
0

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • I ask as I would like to create a function that gets the fd of whatever is passed to it: takes lua file objects, luasocket objects, libev objects, apr objects.... and I need to tell the difference between them to know which routine to use. – daurnimator Oct 23 '11 at 03:25
  • @daurnimator: What is an "fd"? – Nicol Bolas Oct 23 '11 at 03:31
  • @daurnimator: On the assumption that you're on a platform that has file descriptors, you can always use the `pcall` method I suggested. That is, call a "get file descriptor from X" function for each possible type X, but wrap it in a `pcall`. If it fails, then obviously it wasn't type X. Though this would only work if the "get file descriptor from X" functions are all Lua functions. But ultimately, there is no way to be certain that any particular object is from any particular place. – Nicol Bolas Oct 23 '11 at 05:03
  • sure there are ways: cache all metatables used by luasocket and check to see if the metatable of your object matches one of them. Just I was hoping there would be a nicer way – daurnimator Oct 23 '11 at 09:10
  • 2
    Instead of testing types, add the same method (with different implementations) to the method table of all types involved. Then you can simply do `value:mymethod()`. – lhf Oct 23 '11 at 10:38
  • an interesting idea @lhf.... but I never feel clean adding methods to objects I don't 'own' (this code is to go into a library I expect others to use) – daurnimator Oct 23 '11 at 21:42