setmetatable

From Garry's Mod
Jump to: navigation, search
 setmetatable( )

Contents

Description

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

Arguments

table Tab

The table who's metatable to change.

Arguments

table Metatable

The metatable to assign.
If it's nil, the metatable will be removed.

Returns

table

The first argument.

Examples

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"
Personal tools
Navigation