How to find a table's methatable

Viewed 110

Is there a test ( or a magical way) to find out if a table you encounter in a script has a metatable somewhere else in this script or other modules that are being required?? That is without scouring the entire code.

2 Answers

if you want to know for sure:

if getmetatable(some_table) ~= nil then
  print "It has a metatable"
else
  print "It doesn't have a metatable"
end

This detects a metatable even if it has been "hidden" by setting __metatable = false. In case you want to respect this and consider a "hidden" metatable as no metatable at all, you have to also check for false (or just write if getmetatable(some_table) then...)

(Thanks Egor Skriptunoff for pointing that out!)

You will need to read the documentation or source code if you want information on the contents of a metatable.

A table's metatable can be locked by defining __metatable at which point the getmetatable could almost any value that the programmer wanted to return, it can not be set to nil.

Lua-Users Metatable Events

__metatable - Hide the metatable. When "getmetatable( myTable )" is called, if the metatable for myTable has a __metatable key, the value of that key is returned instead of the actual metatable.

There is no guarantee method to that can tell you the contents of a given table's metatable.

edited: to cover nil as a value not possible when a metatable is set, as stated by Nicol Bolas

Related