In the wiki it uses this as a use case for metatables:
local function mathProblem(num)
for i = 1, 20 do
num = math.floor(num * 10 + 65)
end
for i = 1, 10 do
num = num + i - 1
end
return num
end
local metatable = {
__index = function (object, key)
local num = mathProblem(key)
object[key] = num
return num
end
}
local t = setmetatable({}, metatable)
print(t[1]) -- Will be slow because it's the first time using this number, so it has to run the math function.
print(t[2]) -- will be slow because it's the first time using this number.
print(t[1]) -- will be fast because it's just grabbing the number from the table.
BUT I can get the same functionality by doing this:
local t = {}
local function mathProblem(num)
for i = 1, 20 do
num = math.floor(num * 10 + 65)
end
for i = 1, 10 do
num = num + i - 1
end
return num
end
local function checkTable(tab, val)
if not tab[val] then
local num = mathProblem(val)
tab[val] = num
end
return tab[val]
end
print(checkTable(t, 1)) -- Will be slow because it's the first time using this number, so it has to run the math function.
print(checkTable(t, 2)) -- will be slow because it's the first time using this number.
print(checkTable(t, 1)) -- will be fast because it's just grabbing the number from the table.
I’m not sure I understand why it’s needed. For me, it seems like it needlessly adds a layer of complexity. It seems like nothing more than a function that’s called if a value doesn’t exist.
I’ve seen other examples of using different metamethods, but they still seemed replaceable by using a function with a simple if statement. Is there anything that can ONLY be accomplished by metatables/metamethods? If so, I could really use a code example.