lua-users home
lua-l archive

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


On Jun 1, 2011 6:46 PM, "Miles Bader" <miles@gnu.org> wrote:
>
> Tomas Guisasola Gorham <tomas@tecgraf.puc-rio.br> writes:
> >       I think there is no efficient way to check if a given object
> > is callable.  I would say that one should protect-call it and check if
> > it throws an error.  Thus you'd better not check it :-)
>
> isn't it just
>
> function callable (x)
>  return type(x) == 'function' or getmetatable(x).__call
> end
>
> ?
>
> -Miles
>
> --
> One of the lessons of history is that nothing is often a good thing to
> do, and always a clever thing to say.  -- Will Durant
>

That works if you only want to call it right now (maybe it's a callback for data you haven't received yet) and are willing to ignore any errors *other* than the object not being callable (or try to parse the error message). I don't recall offhand exactly what I was doing with that (and don't have access to the code at the moment) but there can be times you want to test for callability without actually calling.

My understanding too is that calling in protected mode is fairly expensive, and getmetatable() only works on tables so you'd have to use debug.getmetatable(), and the debug library is intended only for (well) debugging. I may be wrong about any of those though.

--
Sent from my toaster.