Advertisement
LBPHacker

Lua Memoize

Feb 2nd, 2014
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.78 KB | None | 0 0
  1. function memoizify(memoizified, persistence)
  2.     persistence = type(persistence) == "number" and persistence or 256
  3.     local cache = {}
  4.     return function(...)
  5.         local inargs = {...}
  6.         local outargs
  7.         local useless = {}
  8.         for key, value in pairs(cache) do
  9.             local difference = false
  10.             for ix = 1, #key do
  11.                 if key[ix] ~= inargs[ix] then
  12.                     difference = true
  13.                     break
  14.                 end
  15.             end
  16.             if difference then
  17.                 if persistence > 0 then
  18.                     key[0] = key[0] - 1
  19.                     if key[0] == 0 then useless[#useless + 1] = key end
  20.                 end
  21.             else
  22.                 key[0] = persistence
  23.                 outargs = value
  24.             end
  25.         end
  26.         for ix = 1, #useless do
  27.             cache[useless[ix]] = nil
  28.         end
  29.         if not outargs then
  30.             outargs = {memoizified(...)}
  31.             inargs[0] = persistence
  32.             cache[inargs] = outargs
  33.         end
  34.         return unpack(outargs)
  35.     end
  36. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement