Memoization
Memoization refers to memorizing values already used An example of this is given below
- Note that the __mode will cause the table to be weak
- This is discussed in the section on Garbage Collection and Weak Tables
--[[This is a function and some code that shows the concept of memorization]] local metas = {} setmetatable(metas, {__mode = "kv"}) function setDefault(table, default) local mt = metas[default] if mt == nil then mt = {__index = function() return default end} metas[default] = mt --this is the line that memorizes end setmetatable(table, mt) end planets = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"} local default = "Not in our solar system" setDefault(planets, default) print(planets[3]) print(planets[10]) star = {"Sun"} setDefault(star, default) print(star[1]) print(star[2]) print(getmetatable(planets)) print(getmetatable(star)) print(metas[default])