lua-users home
lua-l archive

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


2018-03-24 10:40 GMT+02:00 Sergey Zakharchenko <doublef.mobile@gmail.com>:
> Dirk,
>
>> > Does pairs() have exclusive rights on calling __pairs()? (Obviously no).
>>
>> Should we extend that logic to __len, __add, __concat etc, or is there
>> something special about __pairs?
>
> Why not? E.g. __len could be placed on tables for forward compatibility and
> called explicitly in Lua 5.1 in some sort of an lpairs() iterator.

I would find that very confusing.

Metamethods are functions called in a situation where otherwise Lua
would signal an error. They are listed in the manual in §2.4 –
"Metatables and Metamethods".

__pairs, __gc and __tostring are not listed there, because they are
not real metamethods. They are functions stored in the metatable whose
names start with '__'.

To call them metamethods is an abuse of terminology. It is much
shorter that for example "a __gc field in the metatable", and
admittedly even the manual is guilty of using it, but it leads people
to expect [1] that metamethods can be used to customize the behaviour
of Lua. They can't. They are fallbacks.

This is not to say that you can't use the same function to be called
by a user program and also as a metemethod. I do it all the time. But
then I give them different names. Functions in Lua are first-class
values, and the property is there to be exploited.

[1] I was a Lua user for several months before I discovered that
__index and __newindex are not called every time you index an array,
they are only called when the key does not exist.