lua-users home
lua-l archive

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


2018-03-24 7:08 GMT+02:00 Egor Skriptunoff <egor.skriptunoff@gmail.com>:
>
> On Sat, Mar 24, 2018 at 3:24 AM, Philipp Janda  wrote:
>>
>> Am 23.03.2018 um 09:41 schröbte Sergey Zakharchenko:
>>>
>>> Dirk,
>>>
>>>>> If __pairs is invoked wth a second argument equal to the special value
>>>>> false, the caller is not interested in values (only in keys), so the
>>>>> returned iterator may returned any value, including nil, or no value
>>>>> at all, for them.
>>>>
>>>>
>>>> You can already write "for k in pairs(tbl,false) do ... end".
>>>
>>>
>>> Sure I can. However, certain kinds of (heavily meta) tables may have a
>>> high cost of value retrieval, which this proposal aims to eliminate.
>>
>>
>> When using the `pairs` function, I expect getting pairs. An iterator factory for keys only would better be called `keys()`. Implementation-wise it could look for a `__keys` metamethod for those performance critical cases and fall back to the `pairs` protocol but dropping the second value.
>
>
> for k in pairs(tbl, 'k') do
> for v in pairs(tbl, 'v') do
> for k, v in pairs(tbl, 'kv') do  -- the default value of second argument

Neat, especially the second one — but the idiom 'for _,v in pairs(tbl)
do' is so well entrenched .

IIUC, the OP's "conservative" proposal is merely that 'pairs' should
not discard extra arguments, i.e. it should trigger __pairs(tbl,...)
rather than just _pairs(tbl).

Since 'pairs' is just an entry in the base libary, one can monkey-patch it.

local _keep_pairs = pairs
pairs = function(tbl,...)
  local meta = getmetatable(tbl)
  if meta then meta = meta.__pairs end
  if meta then return meta(tbl,...)
  else return next,tbl
  end
end

Why change 'pairs' in standard Lua if this is so easy?