mirror of
https://github.com/appgurueu/modlib.git
synced 2024-11-26 01:03:46 +01:00
Add func.memoize
This commit is contained in:
parent
479afb6c88
commit
f4b7eca18f
18
func.lua
18
func.lua
@ -1,6 +1,6 @@
|
|||||||
-- Localize globals
|
-- Localize globals
|
||||||
local error, coroutine, math, modlib, unpack
|
local error, coroutine, math, modlib, unpack, select, setmetatable
|
||||||
= error, coroutine, math, modlib, unpack
|
= error, coroutine, math, modlib, unpack, select, setmetatable
|
||||||
|
|
||||||
-- Set environment
|
-- Set environment
|
||||||
local _ENV = {}
|
local _ENV = {}
|
||||||
@ -35,6 +35,20 @@ function values(...)
|
|||||||
return function() return unpack(args) end
|
return function() return unpack(args) end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
function memoize(func)
|
||||||
|
return setmetatable({}, {
|
||||||
|
__index = function(self, key)
|
||||||
|
local value = func(key)
|
||||||
|
self[key] = value
|
||||||
|
return value
|
||||||
|
end,
|
||||||
|
__call = function(self, arg)
|
||||||
|
return self[arg]
|
||||||
|
end,
|
||||||
|
__mode = "k"
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
-- Equivalent to `for x, y, z in iterator, state, ... do callback(x, y, z) end`
|
-- Equivalent to `for x, y, z in iterator, state, ... do callback(x, y, z) end`
|
||||||
function iterate(callback, iterator, state, ...)
|
function iterate(callback, iterator, state, ...)
|
||||||
local function loop(...)
|
local function loop(...)
|
||||||
|
10
test.lua
10
test.lua
@ -53,6 +53,16 @@ do
|
|||||||
end
|
end
|
||||||
assert(next(tab) == nil)
|
assert(next(tab) == nil)
|
||||||
assert(func.aggregate(func.add, 1, 2, 3) == 6)
|
assert(func.aggregate(func.add, 1, 2, 3) == 6)
|
||||||
|
local called = false
|
||||||
|
local function fun(arg)
|
||||||
|
assert(arg == "test")
|
||||||
|
local retval = called
|
||||||
|
called = true
|
||||||
|
return retval
|
||||||
|
end
|
||||||
|
local memo = func.memoize(fun)
|
||||||
|
assert(memo(arg) == false)
|
||||||
|
assert(memo(arg) == false)
|
||||||
end
|
end
|
||||||
|
|
||||||
-- string
|
-- string
|
||||||
|
Loading…
Reference in New Issue
Block a user