diff options
Diffstat (limited to 'runtime/lua/vim/iter.lua')
-rw-r--r-- | runtime/lua/vim/iter.lua | 26 |
1 files changed, 23 insertions, 3 deletions
diff --git a/runtime/lua/vim/iter.lua b/runtime/lua/vim/iter.lua index 0e98d0437e..245a33625e 100644 --- a/runtime/lua/vim/iter.lua +++ b/runtime/lua/vim/iter.lua @@ -1,7 +1,8 @@ ---@defgroup lua-iter --- ---- The \*vim.iter\* module provides a generic "iterator" interface over tables ---- and iterator functions. +--- @brief The \*vim.iter\* module provides a generic interface for working with +--- iterables: tables, lists, iterator functions, pair()/ipair()-like iterators, +--- and \`vim.iter()\` objects. --- --- \*vim.iter()\* wraps its table or function argument into an \*Iter\* object --- with methods (such as |Iter:filter()| and |Iter:map()|) that transform the @@ -14,6 +15,8 @@ --- - Non-list tables pass both the key and value of each element --- - Function iterators pass all of the values returned by their respective --- function +--- - Tables with a metatable implementing __call are treated as function +--- iterators --- --- Examples: --- <pre>lua @@ -46,6 +49,12 @@ --- return k == 'z' --- end) --- -- true +--- +--- local rb = vim.ringbuf(3) +--- rb:push("a") +--- rb:push("b") +--- vim.iter(rb):totable() +--- -- { "a", "b" } --- </pre> --- --- In addition to the |vim.iter()| function, the |vim.iter| module provides @@ -350,7 +359,7 @@ function ListIter.totable(self) return self._table end ---- Fold an iterator or table into a single value. +--- Fold ("reduce") an iterator or table into a single value. --- --- Examples: --- <pre>lua @@ -889,6 +898,17 @@ end function Iter.new(src, ...) local it = {} if type(src) == 'table' then + local mt = getmetatable(src) + if mt and type(mt.__call) == 'function' then + ---@private + function it.next() + return src() + end + + setmetatable(it, Iter) + return it + end + local t = {} -- Check if source table can be treated like a list (indices are consecutive integers |