Other metamethods

  • __metatable is used to protect an object's metatable
  • __tostring is called to convert the object into a string

If the __metatable index is defined in a metatable, it is no longer possible to use the setmetatable function to change an object's metatable. Calling getmetatable(object) will return the value stored in the __metatable index.

The __tostring metamethod is called by the tostring() function or in any other context where the object would normally be converted into a string such as when the .. operator is used to concatenate two strings together.

Example
mt={}
mt.__metatable = "locked"
mt.__tostring = function(t)
error("Cannot convert to a string!",0)
end

t={}

setmetatable(t,mt)

setmetatable(t,null)	--> error
str = tostring(t)	--> error