@@ -12,6 +12,30 @@ local export, getmetamethod = base.export, base.getmetamethod
1212local M = { " std.lua" }
1313
1414
15+
16+ --[[ ================= ]] --
17+ --[[ Helper Functions. ]] --
18+ --[[ ================= ]] --
19+
20+
21+ local function wrapiterator (factory , ...)
22+ -- Capture wrapped ctrl variable into an upvalue...
23+ local fn , istate , ctrl = factory (... )
24+ -- Wrap the returned iterator fn to maintain wrapped ctrl.
25+ return function (state , _ )
26+ local v
27+ ctrl , v = fn (state , ctrl )
28+ if ctrl then return v end
29+ end , istate , true -- wrapped initial state, and wrapper ctrl
30+ end
31+
32+
33+
34+ --[[ ================= ]] --
35+ --[[ Module Functions. ]] --
36+ --[[ ================= ]] --
37+
38+
1539--- A rudimentary case statement.
1640-- Match `with` against keys in `branches` table, and return the result
1741-- of running the function in the table value for the matching key, or
@@ -42,6 +66,32 @@ export (M, "eval (string)", function (s)
4266end )
4367
4468
69+ --- An iterator over all elements of a sequence.
70+ -- @function elems
71+ -- @tparam sequence x a sequence
72+ -- @treturn function iterator function
73+ -- @treturn sequence *x*, the sequence being iterated over
74+ -- @treturn int *key*, the previous iteration key
75+ -- @usage
76+ -- for v in elems {a = 1, b = 2, c = 5} do process (v) end
77+ export (M , " elems (string|table)" , function (x )
78+ return wrapiterator (getmetamethod (x , " __pairs" ) or pairs , x )
79+ end )
80+
81+
82+ --- An iterator over the integer keyed elements of a sequence.
83+ -- @function ielems
84+ -- @tparam sequence x a sequence
85+ -- @treturn function iterator function
86+ -- @treturn sequence *x*, the sequence being iterated over
87+ -- @treturn int *index*, the previous iteration index
88+ -- @usage
89+ -- for v in ielems {"a", "b", "c"} do process (v) end
90+ export (M , " ielems (List|list|string)" , function (x )
91+ return wrapiterator (getmetamethod (x , " __ipairs" ) or ipairs , x )
92+ end )
93+
94+
4595--- Memoize a function, by wrapping it in a functable.
4696--
4797-- To ensure that memoize always returns the same results for the same
0 commit comments