如何知道一个值是否是一个luasocket对象?
我注意到 luasocket 似乎没有提供一种方法来知道一个值是否是 luasocket 对象。
比较元表的常用方法不起作用,因为不同的套接字对象类型具有不同的元表。 元表中似乎没有任何一致的值可供检查(例如,相同的 __tosting 元方法)
那么:如何知道他们拥有的值是否是 luasocket 对象?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
既然你只想知道它是否是一个 LuaSocket 对象,这样你就可以获取 fd,为什么不直接查看该对象是否有 getfd() 方法呢?作为奖励,这将适用于当前和未来在对象上提供此方法的库,而不仅仅是 LuaSocket。
这种技术称为“鸭子打字”。
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'.
你不知道。一般来说,您应该自己跟踪此类事情。您相信传递给您的对象就是您所期望的那样。如果您不确定,您可以随时使用
pcall
调用它们的函数并捕获任何错误。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.