Wikia

WoWWiki

USERAPI Memorizing table

Talk0
101,556pages on
this wiki

Redirected from Memorizing table

This page documents a user-defined function that you can copy and paste into your addon. Replace <PREFIX> with your AddOn's prefix to avoid conflicts between different versions of these functions.
User defined functions < Memorizing 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 Edit

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 Edit

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. setmetatable 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 names[1234] 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 __index(names, 1234)

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.

Around Wikia's network

Random Wiki