setmetatable

Sets the metatable for a table

Prototype

t = setmetatable (t, metatable)

Description

Sets the metatable for the nominated table. If metatable is nil, removes the metatable. If the original metatable has a "__metatable" entry an error is raised.

Returns the table.

Metatables let you add special entries that cause certain operations to behave in a different way. These operations are (each one starts with 2 underscore characters): If there is no __le metamethod, Lua tries the __lt metamethod, assuming that:

a <= b  is equivalent to:  not (b < a)
Examples:

-- define adding to the table
t = { age = 42, height = 102 }
m = { __add = function (tbl, n) return t.age + n end }
setmetatable (t, m)
print (t + 1)  --> 43

-- define calling the table
t = { age = 42, height = 102 }
m = { __call = function (t) table.foreach (t, print) end }
setmetatable (t, m)
t ()  -- "call" the table (this prints each entry)

-->

height 102
age 42

Lua functions

Topics