How do I use getmetatable() ?
Been stuck on this since docs well are weird
There’s a really nice meta tables and meta methods resource floating around on here. It explained a lot of it very clearly. What are metatables for and how to understand them? - #2 by BenSBk
I already know how metatables work.
Just don’t know what getmetatable() could be used for…
I mean, never saw someone using it.
local MetaTable = setmetatable({},{
__index = function(Self, Index)
print("Hi ".. Index)
end;
})
print(MetaTable.A)
Output
Hi A
getmetatable(MetaTable).__index = function(Self, Index)
print("Now "..Index)
end;
Output
Now A
Deleted again WOOPS;
Set up metatable
local MetaTable = setmetatable({},{
__index = function(Self, Index)
print("Hi ".. Index)
end;
})
print(MetaTable.A)
Output
Hi A
getmetatable( Metatable)
getmetatable(MetaTable).__index = function(Self, Index)
print("Now ".. Index)
end;
print(MetaTable.A)
Output
Now A
Useful if you do not have a reference to a table’s metatable.
Here, we do not have a direct reference to the metatable to which we must use getmetatable if we need it:
local tableWithMetatable = setmetatable({}, {__index = function() end})
Otherwise, you might not need it if you have a variable defined as it’s metatable.
So basically getmetatable is dumb?
It gets the table’s metatable. In practice it’s not very useful, since you probably defined the metatable yourself in the first place, and probably already have a reference to it.
Essentially yes, the only case I could see is getting a script env? Or just perhaps when you lose a reference as stated by @fixmycode
local OldEnv = getfenv()
local Env = setfenv({},{
__index = function(Self, Index)
if OldEnv[Index] == nil then
error("Attempted to Index nil value ".. Index)
else
return OldEnv[Index]
end
})
end;
})
getmetatable(getfenv())
Sorry. I misunderstood what you meant by “How do I use getmetatable()?” I thought you wanted a tutorial on how to use getmetable(). Didn’t realize you were asking for a use case for it. My bad.