Memoizing table

A memoizing table is a normal table with a metatable designed to find missing values and save them. The mechanics are transparent to the caller, it thinks it's just doing a normal lookup.

Memoizing tables are especially handy for caching values which are expensive to lookup or calculate. The developer generally expects that for a given index the value won't change, so it does not need to be recomputed after the first lookup.

Code
For this example, we will cache the name results from a GetItemInfo call.

local names = setmetatable({}, { 	__index = function(t, i) 		local name = GetItemInfo(i) 		if not name then return end 		rawset(t, i, name) 		return name 	end, })

How it works
At first glance, this code is rather arcane. We will dissect it line by line.

local names = setmetatable({}, { This creates a new table  to store values in.  We set the metatable in the lines following this call.    returns back the table passed as the first arg, so we save it.

__index = function(t, i) This is where the real magic begins. If we perform a lookup, for example  the names table is queried for index 1234. If there is a value here it is returned, a plain simple metatable-less lookup. But what if the value is nil? Lua sees our table has a metatable with a __index function, so it calls this function. The table and the requested index are passed, the same as if we had called

local name = GetItemInfo(i) if not name then return end Simple enough, this is where we look up our value, and return out if nothing is found.

rawset(t, i, name) return name If we didn't return out, we found a name. We use rawset to save the value into our table (for future lookups) and we return the result back for the caller's use.