lua-users home
lua-l archive

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

On Mon, May 25, 2009 at 1:38 PM, Peter Cawley wrote:
> On Mon, May 25, 2009 at 6:18 PM, Petite Abeille wrote:
>> Perhaps I'm totally missing the point, but... what's the difference between
>> a function with a metatable and a table with a call metamethod?
> Functors (things which act like functions but are not of type
> function) cannot be passed to [standard] library functions which
> blindly check for a function rather than a callable object.

At times I want to test whether a value "is callable", such as when
checking function arguments.  We can test whether the value is a
function or is a table with a call metamethod or is a userdata or even
string that is made callable.  In the general case, one needs to be
careful if the metatable contains a __metatable field, which makes the
__call metamethod inaccessible.  Furthermore, perhaps make sure you do
a rawget when tesing for __call on the metatable in the rare case that
the metatable itself has a metatable that might trigger some
side-effect on indexing.  So, a fully correct solution is not so
obvious.  We could wrap the call in a try/catch (i.e. pcall), but that
is often not practical nor necessarily correct either.

Maybe Lua would do well to have a function that check for the
existence of an operator on a value:

  function g(f,x)
    assert(hasoperator(f, '__call'), 'f not callable')

BTW, this discussion on giving functions individual metatables has
come up before [1].