缓存运行结果,减少运算

function memoize (f)
    local mem = {}                       -- memoizing table
    setmetatable(mem, {__mode = "kv"})   -- make it weak
    return function (x)       -- new version of ’f’, with memoizing
        local r = mem[x]
        if r == nil then      -- no previous result?
            r = f(x)          -- calls original function
            mem[x] = r        -- store result for reuse
        end
        return r
    end
end

memoize()创建的函数的运算结果可以被缓存:

loadstring = memoize(loadstring)

微信公众号:我的网课 微信公众号:我的资产

results matching ""

    No results matching ""