I’ve been using meta tables for a bit, but I really don’t TRULY understand how they work. What I’m mainly stumped on is the metamethods and setmetatable. I’ve been usually just copy pasting what I’ve seen before and setting up classes in the exact same way. But now, the way I used to do it seems to be getting in the way of my frameworks.
For Example
Lets say I had a a table with an __index
local Index = {}
local Table = {}
Table.__index = Index
And I created a new function in the Index table.
local Index = {}
local Table = {}
Table.__index = Index
function Table.new()
local self = setmetatable({}, Table)
return self
end
function Index:Trigger()
print("Triggered the Index")
end
Yeah that works fine, right? But this is where my issue occurs.
Lets say theres an even LARGER table I want the index to be inside of, named “Framework”. Whenever I call on a method from self, I want self to check through Index, and if it doesn’t find the method or object in Index, it searches through Framework finally. I assumed I’d just have to do this.
local Index = {}
local Table = {}
Table.__index = Index
function Table.new(_FrameworkObject)
Index.__index = _FrameworkObject
local self = setmetatable({}, Table)
return self
end
function Index:Trigger()
print("Triggered the Index")
self:TriggerFrameworkMethod() -- attempt to call missing method "TriggerFrameworkMethod" of table.
end
No? I’m a little lost on how things really go in the woodwork with meta tables.
P.S. I wrote this by hand on-site, so if there are any syntax errors it was NOT on purpose.
EDIT FOR CLARIFICATION OR ANYONE CONFUSED
This method is used only if you want to run functions in a larger table, with the data still from the larger table, but with custom arguments.
local function RouteMeta(Meta, Table)
local self = setmetatable(Table, {__index = function(_, key)
if Meta[key] then
if type(Meta[key]) == 'function' then
return function(...)
Meta[key](Meta, ...)
end
else
return Meta[key]
end
end
end
})
return self
end
local Component = {}
function Component.new(_Framework, ExistingData)
local self = RouteMeta(_Framework, ExistingData or {})
return self
end
return Component
