setmetatable
Example
Creates a metatable and assigns it to a table.
local Pupil_meta = {
GetName = function(self)
return self.name
end
}
Pupil_meta.__index = Pupil_meta
-- If a key cannot be found in an object, it will look in it's metatable's __index metamethod.
local Pupil = {
name = "John Doe"
}
setmetatable(Pupil, Pupil_meta)
print( Pupil:GetName() )
-- This will look for the "GetName" key in Pupil, but it doesn't have one. So it will look in it's metatable (Pupil_meta) __index key instead.
Output: "John Doe"