[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: __call metamethod, misleading doc or am I missing something?
- From: Dirk Laurie <dirk.laurie@...>
- Date: Tue, 21 Feb 2017 09:26:45 +0200
2017-02-21 8:38 GMT+02:00 Daurnimator <quae@daurnimator.com>:
> On 21 February 2017 at 17:26, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>> 2017-02-20 14:15 GMT+02:00 Francisco Olarte <folarte@peoplecall.com>:
>>
>>> Reading "2.4 – Metatables and Metamethods" the only hint I get of
>>> metatable methods needing to be functions is the end of the first
>>> paragraph " Lua checks for a function in the field "__add" of the
>>> value's metatable. If it finds one, Lua calls this function to perform
>>> the addition. ".
>> ...
>>> So, if the metamethod for __call NEEDS to be a real function, I think
>>> it should be clearly indicated in its documentation.
>>
>> The blanket requiremend is that _all_ metamethods should be
>> functions.
>>
>> The two exceptions (__index and __newindex) are very clearly
>> documented. In the first case, it says "Despite the name, the
>> metamethod for this event can be either a function or a table."
>>
>> Since at the entry for __call does not say anything of the kind,
>> the implication is that the metamethod cannot be a table.
>
> The key thing here is use of a function `type(x) == "function" vs
> using a call-able, i.e. an `x()` that does something.
> Lua currently checks the former; but perhaps it should more permissive?
> Being able to treat a table as a function is useful in many contexts.
...
> I think it's an interesting suggestion at least, and I think I could
> be swayed either way.
The OP only asked for the manual to be clearer, but since he clearly
expected this to be legal, we can promote the notion to a suggestion.
Not only tables and functions can be callable: anything can. Especially
userdata.
It's not going to slow up anything. There already is a test for a function,
so the extra code comes in place of an error.
The use of a table in __index and __newindex particularly states that
another metamethod may be triggered, so the feature would be
symmetric.
It would be a powerful addition to the language at no overhead cost.
The implementation may be tricky. The routine tryfuncTM which
at present does the job sits in ldo.c, its comments refer to
luaD_precall, and seem to rely in a hard way on the metamethod
being a function.