From 94894068794dbb99804cda689b6c37e70376c8ca Mon Sep 17 00:00:00 2001 From: Gregory Anders Date: Wed, 19 Apr 2023 07:05:04 -0600 Subject: fix(iter): remove special case totable for map-like tables This was originally meant as a convenience but prevents possible functionality. For example: -- Get the keys of the table with even values local t = { a = 1, b = 2, c = 3, d = 4 } vim.iter(t):map(function(k, v) if v % 2 == 0 then return k end end):totable() The example above would not work, because the map() function returns only a single value, and cannot be converted back into a table (there are many such examples like this). Instead, to convert an iterator into a map-like table, users can use fold(): vim.iter(t):fold({}, function(t, k, v) t[k] = v return t end) --- runtime/doc/lua.txt | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) (limited to 'runtime/doc') diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index 60067f1bc3..8e68e9a792 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -3037,6 +3037,19 @@ Iter:find({self}, {f}) *Iter:find()* Iter:fold({self}, {init}, {f}) *Iter:fold()* Fold an iterator or table into a single value. + Examples: > + + -- Create a new table with only even values + local t = { a = 1, b = 2, c = 3, d = 4 } + local it = vim.iter(t) + it:filter(function(k, v) return v % 2 == 0 end) + it:fold({}, function(t, k, v) + t[k] = v + return t + end) + -- { b = 2, d = 4 } +< + Parameters: ~ • {init} any Initial value of the accumulator. • {f} function(acc:any, ...):A Accumulation function. @@ -3297,9 +3310,7 @@ Iter:totable({self}) *Iter:totable()* The resulting table depends on the initial source in the iterator pipeline. List-like tables and function iterators will be collected into a list-like table. If multiple values are returned from the final stage in - the iterator pipeline, each value will be included in a table. If a - map-like table was used as the initial source, then a map-like table is - returned. + the iterator pipeline, each value will be included in a table. Examples: >lua @@ -3310,9 +3321,13 @@ Iter:totable({self}) *Iter:totable()* -- { { 1, 2 }, { 2, 4 }, { 3, 6 } } vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable() - -- { a = 1, c = 3 } + -- { { 'a', 1 }, { 'c', 3 } } < + The generated table is a list-like table with consecutive, numeric + indices. To create a map-like table with arbitrary keys, use + |Iter:fold()|. + Return: ~ (table) -- cgit