The __index metamethod is only invoked if the index you're searching for is nil. In this case, your Unit class returns a table with the following contents: unit, active, and mode. You later then try to index the object you created with Unit.new, for unit, which already exists, therefore the metamethod will not be invoked.
Also, when you're setting a new __index to your Unit object, you're storing that inside your normal table, not it's metatable. In other words, after your for loop, your Unit object looks like this:
local SBD = {
[script] = {
unit = script;
active = false;
mode = 0;
__index = function: address
}
}
Meanwhile, the metatable to that object still only reads {__index = Unit} So, even if you indexed your object for a key that doesn't exist, it would still print nil because it's not inside the Unit class. If you want to make it so you can invoke __index whenever your object is indexed, you'll have to store everything somewhere else and leave your table empty. After that, you can set __index to a function, do whatever you want, and return the value from the new table you're storing everything in. Example:
local SBD = {}
local Unit = {}
Unit.__index = Unit
local function NewUnit(instance)
local object = {
unit = instance;
active = false;
mode = 0;
}
local interface = setmetatable({}, {
__index = function(self, k)
print("__index invoked")
return object[k]
end;
__newindex = function(self, k, v)
object[k] = v
end
})
SBD[instance] = interface
return interface
end
local unit1 = NewUnit(Instance.new("Script"))
print(unit1.unit)
print(unit1.x)
print(select(2, next(SBD)).unit)
Now no matter what, __index will be invoked because we'll always be indexing an empty table. Hope this helped, if you have any questions, just let me know.
1 comment
Thank you! This helped me so much