Garry's Mod Wiki

setmetatable

  table setmetatable( table Tab, table Metatable )

Description

Sets, changes or removes a table's metatable. Returns Tab (the first argument).

Arguments

1 table Tab
The table who's metatable to change.
2 table Metatable
The metatable to assign.
If it's nil, the metatable will be removed.

Returns

1 table
The first argument.

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"