I have implemented a small utility function that some of you might find useful.
It transforms any regular function into a memoized one.
In Programming in Lua there's a simple implementation of function memoization, but it presents several problems:
- It relies on tostring to generate a "string key" for each cached result. This is bound to handle some inputs problematically.
- It doesn't handle functions returning multiple values
- That solution is tied to a particular problem. My implementation is generic.
Code: Select all
local memoize = require 'memoize' love.graphics.newFont = memoize(love.graphics.newFont) font1 = love.graphics.newFont(13) ... font2 = love.graphics.newFont(13) --> A-HA!
In other words, this function can be used to create "cached versions" of regular functions; functions that that will "remember" the results of previous calls just by looking at the parameter list, and just return the values without performing any calculations.
There are lots of applications - in addition to the resource-loading functions shown above, it can be useful in procedural generation functions (remembering random values), recursive functions, or just plain slow ones.
You might not need this function today. Maybe not tomorrow. But some day, you will need to cache results. On that day, memoize.lua will be there for you.
It is available on this location:
I shall now retire to my lair! Bwahahahaa!