mirror of
https://github.com/appgurueu/modlib.git
synced 2024-11-22 15:23:48 +01:00
Add func.iterate and func.aggregate
This commit is contained in:
parent
eb2db70201
commit
7a82efb75f
25
func.lua
25
func.lua
@ -34,6 +34,31 @@ function values(...)
|
||||
return function() return unpack(args) end
|
||||
end
|
||||
|
||||
-- Equivalent to `for x, y, z in iterator(...) do callback(x, y, z) end`
|
||||
function iterate(callback, iterator, ...)
|
||||
local function _iterate(iterable, state, ...)
|
||||
local function loop(...)
|
||||
if ... == nil then return end
|
||||
callback(...)
|
||||
return loop(iterable(state, ...))
|
||||
end
|
||||
return loop(iterable(state, ...))
|
||||
end
|
||||
return _iterate(iterator(...))
|
||||
end
|
||||
|
||||
-- Does not use select magic, stops at the first nil value
|
||||
function aggregate(binary_func, total, ...)
|
||||
if total == nil then return end
|
||||
local function _aggregate(value, ...)
|
||||
if value == nil then return end
|
||||
total = binary_func(total, value)
|
||||
return _aggregate(...)
|
||||
end
|
||||
_aggregate(...)
|
||||
return total
|
||||
end
|
||||
|
||||
function override_chain(func, override)
|
||||
return function(...)
|
||||
func(...)
|
||||
|
11
test.lua
11
test.lua
@ -16,6 +16,17 @@ setfenv(1, setmetatable({}, {
|
||||
end
|
||||
}))
|
||||
|
||||
-- func
|
||||
do
|
||||
local tab = {a = 1, b = 2}
|
||||
func.iterate(function(key, value)
|
||||
assert(tab[key] == value)
|
||||
tab[key] = nil
|
||||
end, pairs, tab)
|
||||
assert(next(tab) == nil)
|
||||
assert(func.aggregate(func.add, 1, 2, 3) == 6)
|
||||
end
|
||||
|
||||
-- string
|
||||
assert(string.escape_magic_chars"%" == "%%")
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user